gpt4 book ai didi

c# - 使用表达式树生成排序列表

转载 作者:行者123 更新时间:2023-11-30 17:28:00 25 4
gpt4 key购买 nike

我有一个 IQueryable 类型的集合,我需要根据一些动态排序字段对其进行排序。排序字段在列表中。

我编写了以下方法来执行此操作。

public List<T> Order<T>(IQueryable<T> source, List<string> propertyNames)
{

if(propertyNames != null && propertyNames.Count > 0)
{
var param = Expression.Parameter(typeof(T), string.Empty);
var property = Expression.PropertyOrField(param, propertyNames[0]);

var sort = Expression.Lambda(property, param);
MethodCallExpression orderByCall = Expression.Call(typeof(Queryable),"OrderBy",new[] { property.Type },Expression.Quote(sort));
if(propertyNames.Count > 1)
{
foreach(var item in propertyNames)
{
param = Expression.Parameter(typeof(T), string.Empty);
property = Expression.PropertyOrField(param, item);

sort = Expression.Lambda(property, param);

orderByCall = Expression.Call(
typeof(Queryable),
"ThenBy", new[] { typeof(T), property.Type },
orderByCall,
Expression.Quote(sort));
}
}

var results = (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(orderByCall);
if(results != null)
return results.ToList();

}

return null;
}

当我执行 MethodCallExpression orderByCall = Expression.Call(typeof(Queryable),"OrderBy",new[] { property.Type },Expression.Quote(sort)); 我遇到了一些异常

No generic method 'OrderBy' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.

最佳答案

抱歉,对于您的错误,我没有直接的解决方案。

这是一种动态排序数据的替代方法(“保持简单”)。

1) 在项目的某处添加这些扩展方法

public static IOrderedQueryable<TSource> OrderBy<TSource, TProperty>(this IQueryable<TSource> source
, Expression<Func<TSource, TProperty>> expression, bool descending)
{
return !descending ? source.OrderBy(expression) : source.OrderByDescending(expression);
}

public static IOrderedQueryable<TSource> ThenBy<TSource, TProperty>(this IOrderedQueryable<TSource> source
, Expression<Func<TSource, TProperty>> expression, bool descending)
{
return !descending ? source.ThenBy(expression) : source.ThenByDescending(expression);
}

2) 现在您可以循环属性名称列表并在 IQueryable 上应用 OrderBy/ThenBy。

其他想法:您可以调整您的方法,使其接受表达式而不是属性名称字符串。

关于c# - 使用表达式树生成排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53810874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com