c# 扩展LINQ的order by函数支持通过字符串来指定列名并支持多列

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

猜你喜欢

转载自www.cnblogs.com/axel10/p/9240602.html