【问题标题】:How to apply multiple orderby in linq query如何在 linq 查询中应用多个 orderby
【发布时间】:2011-01-06 09:48:50
【问题描述】:

我想在多个列上应用 order by 在 LINQ 中一些升序和其他列降序。我该怎么做?

【问题讨论】:

    标签: linq sorting


    【解决方案1】:
    var sortedCollection =
        from item in collection
        orderby item.Property1, item.Property2 descending, item.Property3
        select item;
    

    【讨论】:

      【解决方案2】:

      借用101 LINQ Samples

      orderby p.Category, p.UnitPrice descending
      

      或作为 Lambda:

      products.OrderBy(p => p.Category).ThenByDescending(p => p.UnitPrice); 
      

      【讨论】:

        【解决方案3】:

        Steven 的回答会起作用,但我更喜欢方法链接而不是声明性 LINQ 语法,例如

        collection
            .OrderBy(e => e.Property1)
            .ThenByDescending(e => e.Property2)
            .ThenBy(e => e.Property3)
        

        【讨论】:

        • 您为什么要这样做? LINQ 比扩展方法和 lambda 更具可读性。
        • 我认为这是一个偏好问题。在读/写代码时,我不喜欢在基于方法的 C# 代码和声明性 LINQ 代码之间进行上下文切换。我发现使用方法链接时更容易阅读和查看发生了什么。此外,最终,编译器会将 LINQ 转换为方法调用,因此我更喜欢直接进入马的嘴,让我的代码更直接地反映在运行时执行(JIT 编译)的语句。
        【解决方案4】:

        应该只是陈述

        orderby x, y descending, z
        

        good old ms examples

        【讨论】:

          【解决方案5】:

          为了完整性,并作为此处其他好的答案的替代品...

          还有一个需要 IComparer 的重载或 OrderBy,如果这是您想要的常见顺序模式,那么您可能希望创建一个实现它的类并将其传递给 orderby 子句,让它处理更多复杂的排序,这样当您以相同的方式排序查询时,它可以重复使用。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-03-03
            • 1970-01-01
            • 2011-07-16
            • 1970-01-01
            • 1970-01-01
            • 2011-07-17
            • 1970-01-01
            相关资源
            最近更新 更多