按类值对 VB.net 列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6478673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting a VB.net List by a class value
提问by Freesn?w
I have a list (i.e. Dim nList as new List(of className)
). Each class has a property named zIndex
(i.e. className.zIndex
). Is it possible to sort the elements of the list by the zIndex variable in all of the elements of the list?
我有一个列表(即Dim nList as new List(of className)
)。每个类都有一个名为zIndex
(即className.zIndex
)的属性。是否可以通过列表的所有元素中的 zIndex 变量对列表的元素进行排序?
回答by vcsjones
Assuming you have LINQ at your disposal:
假设您可以使用 LINQ:
Sub Main()
Dim list = New List(Of Person)()
'Pretend the list has stuff in it
Dim sorted = list.OrderBy(Function(x) x.zIndex)
End Sub
Public Class Person
Public Property zIndex As Integer
End Class
Or if LINQ isn't your thing:
或者如果 LINQ 不是你的东西:
Dim list = New List(Of Person)()
list.Sort(Function(x, y) x.zIndex.CompareTo(y.zIndex))
'Will sort list in place
LINQ offers more flexibility; such as being able to use ThenBy
if you want to order by more than one thing. It also makes for a slightly cleaner syntax.
LINQ 提供了更多的灵活性;例如,ThenBy
如果您想通过不止一种方式订购,则可以使用。它还使语法更简洁。
回答by Guffa
You can use a custom comparison to sort the list:
您可以使用自定义比较对列表进行排序:
nList.Sort(Function(x, y) x.zIndex.CompareTo(y.zIndex))
回答by LarsTech
If not LINQ, then you can implement the IComparable(Of ClassName) to your class:
如果不是 LINQ,那么您可以为您的类实现 IComparable(Of ClassName):
Public Class ClassName
Implements IComparable(Of ClassName)
'Your Class Stuff...
Public Function CompareTo(ByVal other As ClassName) As Integer Implements System.IComparable(Of ClassName).CompareTo
If _ZIndex = other.ZIndex Then
Return 0
Else
If _ZIndex < other.ZIndex Then
Return -1
Else
Return 1
End If
End If
End Function
End Sub
and then from your code:
然后从你的代码:
nList.Sort()