具有多个OrderBy子句的Linq语句不起作用

时间:2012-08-15 13:29:19

标签: .net vb.net linq linq-to-entities

我有一个本地集合,我正在尝试使用Linq进行排序,但返回的内存集合仍然按数字ID列FailureID排序。知道为什么这些OrderBy条款没有生效吗?

对象

Public Class OpenBuildFaultsViewModel

    Public Property FailureID As Int64
    Public Property ModelName As String
    Public Property ZoneName As String
    Public Property Fault As String
    Public Property FaultCode As String
    Public Property FaultCodeDetail As String
    Public Property FaultArea As String
    Public Property MajorAssembly As String
    Public Property SubAssembly As String
    Public Property ComponentAssembly As String
    Public Property BusinessTest As String
    Public Property AuditScore As String
    Public Property Comment As String
    Public Property ShortagePart As String
    Public Property CreatedBy As String
    Public Property FixedByID As Int32
    Public Property FixedByComment As String
    Public Property FixedByFaultRectificationID As Int32

End Class

按订单排序

Function Index() As ActionResult

        Dim data As IEnumerable(Of OpenBuildFaultsViewModel) = Session("Failures")

        Dim model = From fails In data.Where(Function(w) w.FixedByID.Equals(0)).
                                        OrderBy(Function(o) o.MajorAssembly).
                                        OrderBy(Function(o) o.SubAssembly).
                                        OrderBy(Function(o) o.ComponentAssembly).
                                        OrderBy(Function(o) o.BusinessTest).
                                        OrderBy(Function(o) o.FailureID)

        Return View(model)

    End Function

1 个答案:

答案 0 :(得分:7)

如果您想按几个条件订购数据,则必须仅将OrderBy用于第一个标准。对于下一个,您应该使用ThenBy

    Dim model = From fails In data.Where(Function(w) w.FixedByID.Equals(0)).
                                    OrderBy(Function(o) o.MajorAssembly).
                                    ThenBy(Function(o) o.SubAssembly).
                                    ThenBy(Function(o) o.ComponentAssembly).
                                    ThenBy(Function(o) o.BusinessTest).
                                    ThenBy(Function(o) o.FailureID)

如果您每次都使用OrderBy,它会“忘记”之前的订单,并按照后续条件完全重新排序,而忽略之前的订单。

BTW,From fails In部分没用;以下陈述具有相同的含义:

    Dim model = data.Where(Function(w) w.FixedByID.Equals(0)).
                    OrderBy(Function(o) o.MajorAssembly).
                    ThenBy(Function(o) o.SubAssembly).
                    ThenBy(Function(o) o.ComponentAssembly).
                    ThenBy(Function(o) o.BusinessTest).
                    ThenBy(Function(o) o.FailureID)