簡體   English   中英

如何使用.NET 2.0排序列表(類似於LINQ OrderBy)

[英]How do I sort a list using .NET 2.0 (similar to LINQ OrderBy)

如何重寫此函數,使其與現在一樣,但不使用LINQ?

Public Function GetAllConnections() As IEnumerable(Of Connection)
    Return GetAllTcpConnections.Concat(GetAllUdpConnections) _
                               .OrderBy(Function(Conn) Conn.Proto) _
                               .ThenBy(Function(Conn) Conn.State)
End Function

GetAllTcpConnections和GetAllUdpConnections這兩個函數都返回一個As List(Of Connection

我基本上需要此功能來執行與現在相同的操作,而無需使用LINQ,因此我也可以將其與Net Framework 2.0一起使用

作為我的評論,我建議您使用LINQBridge ,但是您似乎不想使用LINQ。

下面是一個如何解決此問題的示例。 首先自己進行連接,然后使用自定義比較器進行排序。

Class ConnectionComparer
    Implements IComparer(Of Connection)

    Public Function Compare(x As Connection, y As Connection) As Integer Implements System.Collections.Generic.IComparer(Of Connection).Compare
        ' Assuming that "Nothing" < "Something"
        If x Is Nothing AndAlso y Is Nothing Then Return 0
        If x Is Nothing AndAlso y IsNot Nothing Then Return 1
        If x IsNot Nothing AndAlso y Is Nothing Then Return -1

        Dim protoCompare As Integer = x.Proto.CompareTo(y.Proto)
        If protoCompare = 0 Then
            Return x.State.CompareTo(y.State)
        Else
            Return protoCompare
        End If
    End Function
End Class

Function GetAllConnections() As IEnumerable(Of Connection)
    ' Concat
    Dim connections As List(Of Connection) = GetAllTcpConnections()
    connections.AddRange(GetAllUdpConnections())
    ' Custom comparer to compare first "Proto" and then "State"
    Dim comparer As New ConnectionComparer()
    connections.Sort(comparer)

    Return connections
End Function

請注意,上面的示例將輸出與使用LINQ的代碼相同的代碼。 但是,在幕后,實現是完全不同的(使用列表而不是IEnumerable(LINQ))。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM