LINQ IEnumerable OrderBy

时间:2013-06-22 12:30:34

标签: c# linq pagination

我正在尝试在数据集上实现过滤/排序/分页。我想通过搜索字符串进行过滤,然后应用排序,然后选择该组的子集作为页面。

代码如下:

IEnumerable<Manufacturer> manufacturers;

if (!String.IsNullOrEmpty(genericSearch))
{
    manufacturers = db.Manufacturers.Where(l => l.Name.Contains(genericSearch));
}

manufacturers = manufacturers.OrderBy(sortColName, sortDir, true); // this won't build. it would
// build if i put 'db.Manufacturers' before the .OrderBy but then i lose my filter. it would 
// also build if i used 'l => l.Name' as the OrderBy parameter but i only have the column name 
//as a string from the client.

manufacturers.Skip(displayStart).Take(displayLength).ToList().ForEach(rec => aaData.Add
 (rec.PropertiesToList())); // this is paging where i can use ToList()

如何使用列名作为字符串进行排序?

1 个答案:

答案 0 :(得分:1)

使用反射的可能方法之一

   public static IEnumerable<T> Sort<T>(this IEnumerable<T> list,
            string column, SortDirection direction = SortDirection.Ascending)
   {
        Func<T, object> selector = p => p.GetType().GetProperty(column).GetValue(p, null);
        return (direction == SortDirection.Ascending
                    ? list.OrderBy(selector)
                    : list.OrderByDescending(selector)
                    );
   }