在C#语言的LINQ查询中按子句构建动态顺序

目录

介绍

背景

使用代码


介绍

很多时候,我们需要在C#中处理类似SQL OrderBy。这将帮助您解决动态排序问题。这是一个OrderBy扩展,它采用类似SQLOrderBy string并对IQueryableIEnumerable集合进行排序。

背景

很高兴有一些信息:

  • yield
  • IQueryable
  • IEnumerable
  • Reflection

使用代码

要使用此扩展,我们只需要传递列表和要在其中对列表进行排序的排序参数。如下:

SortingHelper.SortByClause(list, SortingParms).ToList();

public static class SortingHelper
    {
        private class SortByInfo
        {
            public SortDirection Direction { get; set; }
            public string PropertyName { get; set; }            
            public bool Initial { get; set; }
        }

        private enum SortDirection
        {
            Ascending = 0,
            Descending = 1
        }
        
        public static IEnumerable<T> SortByClause<T>
               (this IEnumerable<T> enumerable, string sortBy)
        {
            return enumerable.AsQueryable().SortBy(sortBy).AsEnumerable();
        }

        public static IQueryable<T> SortBy<T>
               (this IQueryable<T> collection, string sortBy)
        {
            foreach(SortByInfo sortByInfo in ParseOrderBy(sortBy))
                collection = ApplyOrderBy<T>(collection, sortByInfo);

            return collection;
        }
        
        private static IEnumerable<SortByInfo> ParseOrderBy(string sortBy)
        {
            if (String.IsNullOrEmpty(sortBy))
                yield break;

            string[] items = sortBy.Split(',');
            bool initial = true;
            foreach(string item in items)
            {
                string[] pair = item.Trim().Split('-');

                if (pair.Length > 2)
                    throw new ArgumentException(String.Format
                    ("Invalid OrderBy string '{0}'. Order By Format: Property, 
                    Property2-DESC, Property2-ASC",item));

                string prop = pair[0].Trim();

                if(String.IsNullOrEmpty(prop))
                    throw new ArgumentException("Invalid Property. 
                    Order By Format: Property, Property2-DESC, Property2-ASC");
                
                SortDirection dir = SortDirection.Ascending;
                
                if (pair.Length == 2)
                    dir = ("desc".Equals(pair[1].Trim(), 
                          StringComparison.OrdinalIgnoreCase) ? 
                          SortDirection.Descending : SortDirection.Ascending);

                yield return new SortByInfo() { PropertyName = prop, 
                             Direction = dir, Initial = initial };

                initial = false;
            }
        }       

        private static IQueryable<T> ApplyOrderBy<T>
                (IQueryable<T> collection, SortByInfo sortByInfo)
        {
            string[] props = sortByInfo.PropertyName.Split('.');
            Type type = typeof(T);

            ParameterExpression arg = Expression.Parameter(type, "x");
            Expression expr = arg;
            foreach (string prop in props)
            {
                PropertyInfo pi = type.GetProperty(prop);
                expr = Expression.Property(expr, pi);
                type = pi.PropertyType;
            }
            Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
            LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
            string methodName = String.Empty;

            if (!sortByInfo.Initial && collection is IOrderedQueryable<T>)
            {
                if (sortByInfo.Direction == SortDirection.Ascending)
                    methodName = "ThenBy";
                else
                    methodName = "ThenByDescending";
            }
            else
            {
                if (sortByInfo.Direction == SortDirection.Ascending)
                     methodName = "OrderBy";
                else
                     methodName = "OrderByDescending";
            }

            return (IOrderedQueryable<T>)typeof(Queryable).GetMethods().Single(
                method => method.Name == methodName
                        && method.IsGenericMethodDefinition
                        && method.GetGenericArguments().Length == 2
                        && method.GetParameters().Length == 2)
                .MakeGenericMethod(typeof(T), type)
                .Invoke(null, new object[] { collection, lambda });
        }        
    }

希望这会有所帮助!

https://www.codeproject.com/Tips/5334254/Build-Dynamic-Order-by-Clause-in-LINQ-Query-in-Csh

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值