简体   繁体   English

LINQ IE无数订购

[英]LINQ IEnumerable OrderBy

I'm trying to implement filtering/ordering/paging on a data set. 我正在尝试对数据集实施过滤/排序/分页。 I want to filter by a search string, then apply ordering, then select a subset of that set to be a page. 我想按搜索字符串进行过滤,然后应用排序,然后选择该集合的一个子集作为页面。

Code looks like: 代码如下:

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()

How do I do this to allow ordering with the column name as a string? 如何执行此操作以允许将列名称作为字符串进行排序?

One of the possible ways to use reflection 使用反射的可能方法之一

   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)
                    );
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM