Vb.net 如何使用.NET 2.0(类似于LINQ OrderBy)对列表进行排序
如何重写此函数,使其与现在一样,但不使用LINQVb.net 如何使用.NET 2.0(类似于LINQ OrderBy)对列表进行排序,vb.net,linq,sorting,compare,ienumerable,Vb.net,Linq,Sorting,Compare,Ienumerable,如何重写此函数,使其与现在一样,但不使用LINQ Public Function GetAllConnections() As IEnumerable(Of Connection) Return GetAllTcpConnections.Concat(GetAllUdpConnections) _ .OrderBy(Function(Conn) Conn.Proto) _
Public Function GetAllConnections() As IEnumerable(Of Connection)
Return GetAllTcpConnections.Concat(GetAllUdpConnections) _
.OrderBy(Function(Conn) Conn.Proto) _
.ThenBy(Function(Conn) Conn.State)
End Function
GetAllTcpConnections和GetAllUpConnections这两个函数都会将作为列表(连接的列表)返回
我基本上需要这个函数来做和现在一样的事情,不使用LINQ,所以我也可以将它与Net Framework 2.0一起使用。作为我的评论,我建议您使用,但是您似乎不想使用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
类连接比较程序
实现(连接的)IComparer
公共函数Compare(x作为连接,y作为连接)作为整数实现System.Collections.Generic.IComparer(连接的)。Compare
假设“什么都没有”<“什么”
如果x为零,y也为零,则返回0
如果x为零,y也不是零,则返回1
如果x不是零,y也是零,那么返回-1
Dim protoCompare As Integer=x.Proto.CompareTo(y.Proto)
如果protoCompare=0,则
返回x.State.CompareTo(y.State)
其他的
返回协议比较
如果结束
端函数
末级
函数GetAllConnections()作为IEnumerable(属于连接)
“海螺
将连接设置为列表(连接的数量)=GetAllTcpConnections()
connections.AddRange(getAlludConnections())
'用于先比较“Proto”然后比较“State”的自定义比较器'
作为新连接的Dim比较器comparer()
连接.排序(比较器)
返回连接
端函数
请注意,上面的示例将输出与使用LINQ的代码相同的代码。但是在后台,实现是完全不同的(使用列表而不是IEnumerable(LINQ))。您可以在.NET 2.0中获得(部分)LINQ支持。我考虑在没有LINQ的情况下也不使用LINQ桥。难道不可能以某种方式与IComparer完成相同的任务吗/我认为,如果您尝试在没有LINQ的情况下编写代码,那么代码看起来就不那么干净了。我认为使用LinqBridge没有什么问题。你有什么特别的理由不想使用它吗?嗯,我个人不喜欢Linq,我希望它在没有Linq的情况下工作,这样我个人就能更好地理解它。您将如何使用List.Sort()实现这一点?