修改后的OrderBy扩展名还可以处理ThenBy

时间:2020-10-02 20:00:19

标签: c#

我有这个扩展程序,它可以处理OrderBy和一堆asc / desc字符串,它的工作原理就像一个魅力:

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();

任何有关此操作的提示将不胜感激。

1 个答案:

答案 0 :(得分:1)

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