c# Linq 使用 Expression Tree 创建自定义排序
参考资料:
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); }