linq 动态排序有问题,无法正常工作

h6my8fg2  于 2023-01-15  发布在  其他
关注(0)|答案(2)|浏览(140)

我有一个函数用来动态地执行OrderBy()

internal static Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> GetOrderBy(List<(string, bool)> orderColumnsAndIsDesc)
{

    bool IsFirst = true;
    MethodCallExpression resultExp = null;
    string methodName;
    LambdaExpression finalLambda = null;
    
    foreach (var item in orderColumnsAndIsDesc)
    {
        string prop = item.Item1;
        string orderType = item.Item2 == true ? "asc" : "desc";
        Type typeQueryable = typeof(IQueryable<TEntity>);
        ParameterExpression argQueryable = Expression.Parameter(typeQueryable, "p");
        var outerExpression = Expression.Lambda(argQueryable, argQueryable);
        IQueryable<TEntity> query = new List<TEntity>().AsQueryable<TEntity>();
        Type type = typeof(TEntity);
        ParameterExpression arg = Expression.Parameter(type, "x");
        Expression expr = arg;
        PropertyInfo pi = type.GetProperty(prop, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
        expr = Expression.Property(expr, pi);
        type = pi.PropertyType;
        LambdaExpression lambda = Expression.Lambda(expr, arg);
        
        if (IsFirst)
        {
            methodName = orderType == "asc" ? "OrderBy" : "OrderByDescending";
            resultExp =
            Expression.Call(typeof(Queryable), methodName, new Type[] { typeof(TEntity), type }, outerExpression.Body, Expression.Quote(lambda));
        }
        else
        {
            methodName = orderType == "asc" ? "ThenBy" : "ThenByDescending";
            resultExp =
           Expression.Call(typeof(Queryable), methodName, new Type[] { typeof(TEntity), type }, resultExp, Expression.Quote(lambda));
        }
        
        finalLambda = Expression.Lambda(resultExp, argQueryable);
        
        IsFirst = false;
    }
   
    return (Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>>)finalLambda.Compile();
}

当有一个项目要排序时,它可以正常工作,但当有多个项目时,它会给出错误。其错误:
系统操作无效异常:从范围""引用了类型为"System.Linq.IQueryable'1 [CMS. Data. Models. Category]"的变量"p",但未定义该变量
我不知道怎么修,请帮帮我。

rseugnpd

rseugnpd1#

试试这个:

public static class IEnumerableExtensions {
    public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, params Tuple<string, bool>[] sortDefinitions)
        => OrderBy<T>(source, sortDefinitions.Select(i => new Tuple<Func<T, object>, bool>(GetPropertyLambda<T>(i.Item1), i.Item2)).ToArray());

    //you can try use lambda direcly in params
    public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, params Tuple<Func<T, object>, bool>[] sortDefinitions) {
        if(source?.Any() ?? false) {
            var items = source;
            foreach(var sortDefinition in sortDefinitions)
                if(items is IOrderedEnumerable<T> ordered)
                    //thenby
                    items = sortDefinition.Item2 ? ordered.ThenBy(sortDefinition.Item1) : ordered.ThenByDescending(sortDefinition.Item1);
                else
                    items = sortDefinition.Item2 ? items.OrderBy(sortDefinition.Item1) : items.OrderByDescending(sortDefinition.Item1);
            return items;
        } else
            return source;
    }

    //based on your code
    private static Func<T, object> GetPropertyLambda<T>(string propertyName) {
        Type type = typeof(T);
        ParameterExpression arg = Expression.Parameter(type, "x");
        Expression expr = arg;
        PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
        expr = Expression.Property(expr, pi);
        return (Func<T, object>) Expression.Lambda(expr, arg).Compile();
    }
}
92vpleto

92vpleto2#

如果使用扩展方法ApplyOrderBy,则可以按以下方式编写函数:

public static Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> GetOrderBy<TEntity>(
    IEnumerable<(string, bool)> order)
{
    return query => (IOrderedQueryable<TEntity>)query
       .ApplyOrderBy(order.Select(t => Tuple.Create(t.Item1, t.Item2)));
}

相关问题