我是VB.Net的新手,我正在使用.Net Framework 2.0。我在VB.Net中有一个自定义对象,带有一些复杂的层次结构
考虑这是我的对象层次结构
Person
Addresses
Address[1]
S.No 1
Street
....
Address[2]
S.No 2
Street
....
Address[3]
**S.No 4**
Street
....
Address[4]
**S.No 3**
Street
....
现在我想基于S.No对Address对象集合进行排序。我期待最终输出如下:
Person
Addresses
Address[1]
S.No 1
Street
....
Address[2]
S.No 2
Street
....
Address[3]
**S.No 3**
Street
....
Address[4]
**S.No 4**
Street
....
答案 0 :(得分:0)
如果"地址"您可以使用Array.Sort(T(), IComparer(Of T))
来完成您的任务。是一个数组。如果是列表,您可以使用list.Sort(IComparer(Of T))
方法。
示例代码为:
Class AddressComparer
Implements IComparer(Of Address)
Public Function Compare(x As Address, y As Address) As Integer Implements System.Collections.Generic.IComparer(Of Address).Compare
' Don't forget to handle "Nothing" values
Return x.No.CompareTo(y.No)
End Function
End Class
Sub Main()
Dim addressesArray() As Address = New Address(3) {}
addressesArray(0) = New Address(1, "1")
addressesArray(1) = New Address(2, "2")
addressesArray(2) = New Address(4, "4")
addressesArray(3) = New Address(3, "3")
Array.Sort(addressesArray, New AddressComparer())
Dim addressesList As New List(Of Address)()
addressesList.Add(New Address(1, "1"))
addressesList.Add(New Address(2, "2"))
addressesList.Add(New Address(4, "4"))
addressesList.Add(New Address(3, "3"))
addressesList.Sort(New AddressComparer())
End Sub