开发者

IList - LINQ to filter and order by

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 开发者_Python百科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.


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
}


    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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜