IList - LINQ过滤和排序依据

时间:2010-01-11 11:30:35

标签: c# linq linq-to-objects generic-list

我有以下测试代码来搜索通用列表:

public void DoSearch(string searchTerm)
{

IList<MyEntity> entities = GetCollectionOfEntities();

IList<MyEntity> results = entities.Where(d => d.Description.Contains(searchTerm)).ToList();

}

我想通过参数传递一个订单(这将是MyEntity的一个属性),当然也可以根据它来命令我的结果。我知道LINQ使用OrderBy但不了解如何通过MyEntity的属性进行排序。

2 个答案:

答案 0 :(得分:10)

您只需使用Func<TSource,TKey>指定要订购的媒体资源:

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
}

答案 1 :(得分:0)

    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是要排序的属性的类型。否则你可以像这样使用Generic:

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

并称之为。