1. 程式人生 > >c# 擴展LINQ的order by函數支持通過字符串來指定列名並支持多列

c# 擴展LINQ的order by函數支持通過字符串來指定列名並支持多列

排序 descend ID ide cti then tps class IT

本文借鑒了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"格式的字符串即可實現多列排序。

c# 擴展LINQ的order by函數支持通過字符串來指定列名並支持多列