c# - 修改 OrderBy 的扩展以处理 ThenBy
问题描述
我有这个扩展,它OrderBy
与 asc/desc 的 bool 一起处理,它就像一个魅力:
public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource, TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}
public static IOrderedQueryable<TSource> OrderByWithDirection<TSource, TKey>
(this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}
但我也需要它来处理ThenBy
(连同 asc/desc 的布尔值)
当前的语法是:
bool primaryDescending = false;
var sortedList = unSortedList
.OrderByWithDirection(o => o.primary, primaryDescending)
.ToList();
我想要的是扩展处理类似这样的语法:
bool primaryDescending = false;
bool secondaryDescending = true;
var sortedList = unSortedList
.OrderByWithDirection(o => o.primary, primaryDescending)
.ThenByWithDirection(o => o.secondary, secondaryDescending)
.ToList();
任何有关如何做到这一点的提示将不胜感激。
解决方案
您只需要定义IOrderedQueryable.ThenByWithDirection
它调用ThenBy___
而不是OrderBy___
:
public static IOrderedEnumerable<TSource> ThenByWithDirection<TSource, TKey>
(this IOrderedEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool descending)
{
return descending ? source.ThenByDescending(keySelector)
: source.ThenBy(keySelector);
}
public static IOrderedQueryable<TSource> ThenByWithDirection<TSource, TKey>
(this IOrderedQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool descending)
{
return descending ? source.ThenByDescending(keySelector)
: source.ThenBy(keySelector);
}
推荐阅读
- python - rpy2错误加载给定正确目录的特定包
- c++ - g++ 在多个文件上与使用 Google 模拟的单一文件相比要慢得多
- bash - 2 个符合 ISO - 8601 标准的日期之间的时差
- vue.js - Vue 没有在组件中定义
- node.js - AWS Lambda 开发工作流程
- shell - 查找从文件目录中的文件获取的模式
- javascript - PHP中的自动数组
- sql - 如何将两张表合二为一?
- webview - Flutter:如何在 WebView 加载页面之前显示 CircularProgressIndicator?
- python - 确定文件是“更可能”是 json 还是 csv