c# - 通用 linq 排序方法 - 解析表达式

标签 c# linq

我最终编写了很多看起来像这样的代码

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/

相关文章:

c# - Visual Studio 加载项 : How do I know when a solution has finished loading

c# - 使用 Linq 对交错数组(求和、平均值、其他函数)进行列操作

c# - 从 List<T> 的 List<T> 筛选

c# - 使用 WIX 3.5 在 IIS 7/7.5 中添加/启用处理程序映射

c# - Nuget.Server 可以列出包,但在包安装时出现 404

c# - 仅为 WPF 中禁用的文本框设置默认文本

c# - 如何使用 DateTime.DaysInMonth 将一个月中的天数填充到组合框

c# - 更新 IEnumerable 中的项目属性但该属性未保持设置?

c# - 使用 LINQ to SQL 匹配特定日期的所有行

c# - Linq to EF - 不支持的函数