c# Linq 使用 Expression Tree 创建自定义排序

参考资料: 

http://blogs.msdn.com/b/swiss_dpe_team/archive/2008/06/05/composable-linq-to-sql-query-with-dynamic-orderby.aspx

http://www.codeproject.com/Articles/230353/An-Example-to-Use-jQuery-Grid-Plugin-in-MVC-Part-1

public static IQueryable<T> OrderByField<T>(this IQueryable<T> data, string fieldName, bool desc)
        {            
            if (fieldName==null || typeof(T).GetProperty(fieldName)== null)
                return data;

            var type = typeof(T);
            var property = type.GetProperty(fieldName);
            var param = Expression.Parameter(typeof(T), "i");
            var propertyAcess = Expression.MakeMemberAccess(param, property);
            var sortExpression = Expression.Lambda(propertyAcess, param);

            var cmd = desc ? "OrderByDescending" : "OrderBy";

            var result = Expression.Call(
                typeof(Queryable),
                cmd,
                new Type[] { type, property.PropertyType },
                data.Expression,
                Expression.Quote(sortExpression));
            
            return data.Provider.CreateQuery<T>(result);            
        }
原文地址:https://www.cnblogs.com/dabaopku/p/2549945.html