C# LINQ IEnumerable OrderBy

C# LINQ IEnumerable OrderBy,c#,linq,pagination,C#,Linq,Pagination,我试图在数据集上实现过滤/排序/分页。我想通过搜索字符串进行筛选,然后应用排序,然后选择该集合的子集作为页面 代码如下所示: IEnumerable<Manufacturer> manufacturers; if (!String.IsNullOrEmpty(genericSearch)) { manufacturers = db.Manufacturers.Where(l => l.Name.Contains(genericSearch)); } manufact

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

代码如下所示:

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

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

使用反射的可能方法之一

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

可能是重复的谢谢。我希望有一个更简单的解决方案,甚至是一个替代方法。可能重复使用双向飞碟的解决方案-它比其他任何解决方案都快。好的,我已经成功地使它工作了。我还向Jon Skeet的解决方案中添加了一个“OrderByPropertyDescending”方法。但是这个安全吗?在他的代码中,他对TODO进行了注释:大量验证: