首页 > 解决方案 > 修改 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();

任何有关如何做到这一点的提示将不胜感激。

标签: c#

解决方案


您只需要定义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);
}

推荐阅读