Reputation: 5419
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?
}
Upvotes: 2
Views: 208
Reputation: 1503280
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?
Upvotes: 3
Reputation: 3274
You should use the built in Linq method var orderedList = myList.OrderBy(x => x.Username)
You shouldn't need to write your own extension method to sort a list.
Upvotes: 2