开发者

Sorting a VB.net List by a class value

开发者 https://www.devze.com 2023-03-15 14:47 出处:网络
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 var

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?


Assuming you have LINQ at your disposal:

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:

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.


You can use a custom comparison to sort the list:

nList.Sort(Function(x, y) x.zIndex.CompareTo(y.zIndex))


If not LINQ, then you can implement the IComparable(Of ClassName) to your class:

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()
0

精彩评论

暂无评论...
验证码 换一张
取 消