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

时间:2010-03-29 06:23:42

标签: 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);

5 个答案:

答案 0 :(得分: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);
}

,同样适用于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);
}

答案 1 :(得分:2)

您可以将查询拆分为多个位,并使用控制流逻辑。 LINQ to SQL将神奇地构造正确的查询,就像你输入了所有的一行一样!这样做的原因是,在您请求数据之前,查询不会发送到数据库,而是存储为表达式。

var linq = new NorthwindDataContext();
var query = linq.Customers
    .Where(c => c.ContactName.StartsWith("a"))
    .SelectMany(cus=>cus.Orders);

IOrderedQueryable<Order> query2;
if (useAscending) {
    query2 = query.OrderBy(ord => ord.OrderDate);
} else {
    query2 = query.OrderByDescending(ord => ord.OrderDate);
}

var query3 = query2.Select(ord => ord.CustomerID);

答案 2 :(得分:1)

return from T in bk.anbarsabts
       where T.kalaname == str
       orderby T.date descending
       select new { T.date, T.kalaname, T.model, T.tedad };

答案 3 :(得分:0)

对于数字等,您通常可以否定'排序变量'。

DateTime,我不太确定。您可以尝试使用Timespan

答案 4 :(得分:0)

好吧,如果您有条件决定订单是升序还是降序,您可以使用此

var query1 = linq.Customers
.Where(c => c.ContactName.StartsWith("a"))
.SelectMany(cus=>cus.Orders)

if(SortAscending)
   query1 = query1.OrderBy(ord => ord.OrderDate);
else
   query1 = query1.OrderByDescending(ord => ord.OrderDate);

var query2 = query1.Select(ord => ord.CustomerID);