views:

1019

answers:

2

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.

+5  A: 

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
}
LukeH
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)...?
youwhut
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
Benjamin Podszun
Excellent. Cheers for the help.
youwhut
@youwhut: You'd need to pass the `Func<S,K>` into the method itself. I've updated the answer to demonstrate.
LukeH
A: 
    public void DoSearch(string searchTerm, Func<MyEntity, PropertyType> selector)

{

IList entities = GetCollectionOfEntities();

IList results = entities .Where(d => d.Description.Contains(searchTerm)) .OrderBy(selector) .ToList();

}

DoSearch("searchTerm", entity => entity.Property)

PropertyType is the type of the property you want to sort. Else you could make it Generic like this:

    public void DoSearch<TKey>(string searchTerm, Func<MyEntity, Tkey> selector)

And call it.