LINQ使用字符串进行排序

/// <summary>
    /// Queryable 扩展类
    /// </summary>
    internal static class OrderByHelper
    {
        private static Dictionary<string, LambdaExpression> _Cache = new Dictionary<string, LambdaExpression>();

        /// <summary>
        /// OrderBy 扩展方法
        /// </summary>
        public static IQueryable<T> OrderBy<T>(this IQueryable<T> superset, string propertyName, bool isDesc)
        {
            dynamic expression = ToLambda<T>(propertyName);
            if (expression != null)
            {
                return isDesc ? Queryable.OrderByDescending(superset, expression) : Queryable.OrderBy(superset, expression);
            }

            return superset;
        }

        private static LambdaExpression ToLambda<T>(string sortName)
        {
            var type = typeof(T);
            var key = $"{type.Name}.{sortName}";
            if (!_Cache.TryGetValue(key, out LambdaExpression value))
            {
                foreach (var property in type.GetProperties())
                {
                    if (property.Name.ToLower() == sortName.SafeToString().ToLower())
                    {
                        var parameter = Expression.Parameter(type);
                        var body = Expression.Property(parameter, property);
                        value = Expression.Lambda(body, parameter);
                        _Cache[key] = value;
                        break;
                    }
                }

                if (value == null)
                {
                    foreach (var property in type.GetProperties())
                    {
                        if (property.PropertyType == typeof(IEnumerable<JsonEntity>))
                        {
                            Expression<Func<T, string>> expression = t => ((IEnumerable<JsonEntity>)property.GetValue(t)).Where(c => c.K == sortName).Select(c => c.V).FirstOrDefault();
                            _Cache[key] = expression;
                        }
                    }
                }
            }

            return value;
        }
    }

版权声明:本文为qq_37319035原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。