LINQ查询需要在同一查询中升序或降序

Vin*_*cio 6 c# linq

反正这个代码可以重构吗?唯一的区别是订单的顺序.

Idealy我想使用委托/ lambda表达式,因此代码是可重用的,但我不知道如何有条件地添加和删除查询运算符OrderBy和OrderByDescending

var linq = new NorthwindDataContext();

        var query1 = linq.Customers
            .Where(c => c.ContactName.StartsWith("a"))
            .SelectMany(cus=>cus.Orders)
            .OrderBy(ord => ord.OrderDate)
            .Select(ord => ord.CustomerID);

        var query2 = linq.Customers
            .Where(c => c.ContactName.StartsWith("a"))
            .SelectMany(cus => cus.Orders)
            .OrderByDescending(ord => ord.OrderDate)
            .Select(ord => ord.CustomerID);
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 12

您可以创建自己的可重用扩展方法,它将执行此操作:

public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool ascending)
{
     return ascending ? source.OrderBy(keySelector)
          : source.OrderByDescending(keySelector);
}
Run Code Online (Sandbox Code Playgroud)

同样适用于ThenBy:

public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>
    (this IOrderedQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool ascending)
{
     return ascending ? source.ThenBy(keySelector)
          : source.ThenByDescending(keySelector);
}
Run Code Online (Sandbox Code Playgroud)