本文借鉴了https://blog.csdn.net/lan_liang/article/details/68523451。
将字符串转换为orderby的linq可以极大地减少重复劳动,可是该怎样将多个字段转换为Order()及ThenBy()表达式呢?可以参照以下代码:
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> q, string condition) { string[] conditions = condition.Split(‘,‘); if (conditions.Length==0) { return (IOrderedQueryable<T>) q; } IOrderedQueryable<T> res = null; for (int i = 0; i < conditions.Length; i++) { string[] strings = conditions[i].Split(" "); var fieldName = strings[0]; var direction = strings[1]; var param = Expression.Parameter(typeof(T), "p"); var prop = Expression.Property(param, fieldName); var exp = Expression.Lambda(prop, param); string method; if (i==0) { method = direction.ToLower() == "asc" ? "OrderBy" : "OrderByDescending"; } else { method = direction.ToLower() == "asc" ? "ThenBy" : "ThenByDescending"; } Type[] types = { q.ElementType, exp.Body.Type }; var mce = i==0? Expression.Call(typeof(Queryable), method, types, q.Expression, exp): Expression.Call(typeof(Queryable), method, types, res.Expression, exp); if (conditions.Length == 1) { return (IOrderedQueryable<T>)q.Provider.CreateQuery<T>(mce); } res = i == 0 ? (IOrderedQueryable<T>) q.Provider.CreateQuery<T>(mce) : (IOrderedQueryable<T>)res.Provider.CreateQuery<T>(mce); } return res; }
IQueryable对象调用Orderby方法,传入"Id desc,Age desc"格式的字符串即可实现多列排序。
原文地址:https://www.cnblogs.com/axel10/p/9240602.html
时间: 2024-10-11 16:49:15