2012-08-15 84 views
3

我有一個本地集合,我試圖用Linq排序,但返回的內存集合仍然保持按數字ID列FailureID排序。任何想法爲什麼這些OrderBy子句沒有生效?通過幾個標準Linq語句與多個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 

回答

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時,它都會「忘記」先前的順序和重新排序完全由後續的標準,而忽略以前的。

順便說一句,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) 
+0

謝謝Thomas, – 2012-08-15 13:34:16