【问题标题】:How do I sort a list using .NET 2.0 (similar to LINQ OrderBy)如何使用 .NET 2.0 对列表进行排序(类似于 LINQ OrderBy)
【发布时间】:2014-03-30 12:08:49
【问题描述】:

我怎样才能重写这个函数,让它像现在一样做同样的事情,但不使用 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 在 .NET 2.0 中获得(部分)LINQ 支持。
  • 我考虑过不使用 LINQ,也不使用 LINQ-Bridge。是否有可能以某种方式使用 IComparer 完成相同的任务? ://
  • 我认为如果您尝试在没有 LINQ 的情况下编写代码,代码看起来会不那么干净。我认为使用 LinqBridge 没有什么问题。你有什么特别的理由不想使用它吗?
  • 好吧,我个人不喜欢 Linq,我希望它在没有 LINQ 的情况下也能工作,然后我个人可以更好地理解它。你会怎么用 List.Sort() 这可能吗?

标签: vb.net linq sorting compare ienumerable


【解决方案1】:

作为我的评论,我建议您使用LINQBridge,但是您似乎不想使用 LINQ。

以下是如何解决此问题的示例。首先自己进行 concat,然后使用自定义比较器进行排序。

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 的代码相同的内容。然而在底层,实现是完全不同的(使用 Lists 而不是 IEnumerable (LINQ))。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多