我最终编写了很多看起来像这样的代码
var ordered = isDescending ? queryable.OrderByDescending(x => x.ID) : queryable.OrderBy(x => x.ID)
但具有不同的表达式,例如 x => x.DateOfBirth 等。我想做的是将其放在一个通用扩展方法中,我可以解析我的表达式,并且 bool 值 isDescending 到,但我不确定这个怎么做。类似的东西
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, Expression<Func<T, TKey>> func, bool isDescending) {
return isDescending ? source.OrderByDescending(func) : source.OrderBy(func);
}
谁能告诉我该怎么做?最好有解释,以便我能理解。
最佳答案
你已经很接近了 - 你只是缺少一个类型参数:
public static IOrderedQueryable<T> OrderBy<T, TKey>(
this IQueryable<T> source, Expression<Func<T, TKey>> func, bool isDescending) {
return isDescending ? source.OrderByDescending(func) : source.OrderBy(func);
}
您的代码之前无法运行,因为 func
参数的类型使用了 TKey
,而这不是方法声明中的类型参数之一。以上应该可以正常工作。
关于c# - 通用 linq 排序方法 - 解析表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1392962/