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
}
Share:
20,537
youwhut
Author by

youwhut

Software developer in the finance sector.

Updated on January 14, 2020

Comments

  • youwhut
    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
    youwhut over 14 years
    Okay 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
    Benjamin Podszun over 14 years
    Not 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
    youwhut over 14 years
    Excellent. Cheers for the help.
  • LukeH
    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
    Jéf Bueno over 8 years
    @LukeH what's the reason to use TKey?