简体   繁体   中英

C# Linq in extension / method

Greetings

I'm looking for creating a extension method including a linq query. What i'm looking for is either a method or extension method which can do something like this

var orderedList = OrderThisList<ModelName>(List<T> sourceList, //and something like m=>m.Username); 

Where ModelName is the entity and Username is the field of which I want to order. The method would look something like

public List<T> OrderThisList<T>(//some linq property?)
{
    //What code goes here?
}

EDIT: It's still extremely unclear what this question is all about, but it sounds like we're dealing with in-memory collections rather than LINQ to SQL etc.

If the problem with using OrderBy is that it doesn't sort the list in-place, you should be using List<T>.Sort() , possibly passing in a custom comparator.

My MiscUtil project has a few helper types which may help you. For example:

var comparison = ProjectionComparer<ModelType>.Create(m => m.SomeProperty)
                                              .ThenBy(m => m.SomeOtherProperty);
list.Sort(comparison);

If you're using LINQ to SQL and you've got a data context , you could use:

public List<TSource, TKey> OrderThisList<TSource, TKey>(
    Expression<Func<TSource, TKey>> ordering)
{
    return dataContext.GetTable<TSource>()
                      .OrderBy(ordering)
                      .ToList();
}

Now obviously that requires two type arguments, and you only want to specify one. There are various ways round this - basically you'd want to end up with a generic type and a method with one type argument ( TKey ) which can be inferred. For example:

var list = Orderer<ModelType>.Create(dataContext)
                             .OrderThisList(m => m.SomeProperty);

It's somewhat round-the-houses though considering that OrderBy is already available... could you explain why you want this, and also what LINQ provider is involved?

您应该使用内置的Linq方法var orderedList = myList.OrderBy(x => x.Username)您不需要编写自己的扩展方法即可对列表进行排序。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM