Question

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.

Was it helpful?

Solution

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
}

OTHER TIPS

    public void DoSearch(string searchTerm, Func<MyEntity, PropertyType> selector)
    {

       IList<MyEntity> entities = GetCollectionOfEntities();

       IList<MyEntity> 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top