首页 > Windows开发 > 详细

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

时间:2018-06-28 21:00:00      阅读:266      评论:0      收藏:0      [点我收藏+]

本文借鉴了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函数支持通过字符串来指定列名并支持多列

原文:https://www.cnblogs.com/axel10/p/9240602.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!