2013-06-22 91 views
0

我试图在数据集上实现过滤/排序/分页。我想按照搜索字符串进行过滤,然后应用排序,然后选择该集的一个子集作为页面。LINQ IEnumerable OrderBy

代码如下所示:

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

如何做到这一点,以便与列名作为字符串的排序?

+0

可能重复[获取动态排序依据Linq中(http://stackoverflow.com/questions/16077490/get-dynamic-orderby-in-linq ) –

+0

谢谢。希望获得更简单的解决方案或其他方法。 – user982119

+0

[LINQ动态分类]的可能的重复(http://stackoverflow.com/questions/4726047/dynamically-sorting-with-linq) – Hogan

回答

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