【问题标题】:how to add sort direction with linq for sql?如何使用 linq 为 sql 添加排序方向?
【发布时间】:2009-11-11 16:43:55
【问题描述】:

假设我有 linq 表达式 q,那么我想给这个查询添加一个排序:

q = q.OrderBy(p => p.Total);

但是对于排序,SQL 有 desc/asc 选项,如何在上面的 linq 表达式中添加它?

【问题讨论】:

    标签: .net linq linq-to-sql sorting


    【解决方案1】:

    还有另一种方法,OrderByDescending

    可能有点矫枉过正,但如果你真的希望能够传递一个指示排序顺序的参数,你可以创建一个扩展方法:

    public static IOrderedEnumerable<TResult> OrderBy<TResult,TKey>(this IEnumerable<TResult> source, Func<TResult, TKey> keySelector, bool ascending)
    {
       Func<Func<TResult, TKey>, IOrderedEnumerable<TResult>> orderMethod = source.OrderBy;
    
       if(!ascending)
          orderMethod = source.OrderByDescending;
    
       return orderMethod.Invoke(keySelector);
    }
    

    这样你就可以做到

    bool ascending = true;
    list.OrderBy(item => item.Name, ascending);
    

    【讨论】:

      【解决方案2】:

      OrderBy将按升序排序,降序使用OrderByDescending

      q = q.OrderByDescending(p => p.Total);
      

      如果您想按多列排序,请使用ThenByThenByDescending 方法。

      q = q.OrderBy(p => p.Col1).ThenByDescending(p => p.Col2);
      

      【讨论】:

        猜你喜欢
        • 2010-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 2010-09-16
        • 1970-01-01
        相关资源
        最近更新 更多