IList - LINQ to filter and order by
20,537
You just use a Func<TSource,TKey>
to specify the property that you want to order by:
DoSearch("foo", e => e.SomeProperty);
// ...
public void DoSearch<TKey>(string searchTerm, Func<MyEntity, TKey> orderBy)
{
IList<MyEntity> entities = GetCollectionOfEntities();
IList<MyEntity> results = entities
.Where(e => e.Description.Contains(searchTerm))
.OrderBy(orderBy)
.ToList();
// etc
}
Comments
-
youwhut over 4 years
I have the following test code to search a generic list:
public void DoSearch(string searchTerm) { IList<MyEntity> entities = GetCollectionOfEntities(); IList<MyEntity> results = entities.Where(d => d.Description.Contains(searchTerm)).ToList(); }
I want to pass an order by parameter (which would be a property of MyEntity) and of course order my results based on that. I understand LINQ uses OrderBy but do not understand how to order by a property of MyEntity.
-
youwhut over 14 yearsOkay this is a good start but how would I go about passing this as a parameter so that my method signature would be public void DoSearch(string searchTerm, orderby)...?
-
Benjamin Podszun over 14 yearsNot at all or using Reflection (which is slow and probably not useful in general). The Func<> way is really the best way to go here imo. +1
-
youwhut over 14 yearsExcellent. Cheers for the help.
-
LukeH over 14 years@youwhut: You'd need to pass the
Func<S,K>
into the method itself. I've updated the answer to demonstrate. -
Jéf Bueno over 8 years@LukeH what's the reason to use
TKey
?