Sorting a VB.net List by a class value

前端 未结 3 928
误落风尘
误落风尘 2021-02-04 00:37

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

3条回答
  •  被撕碎了的回忆
    2021-02-04 00:52

    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.

提交回复
热议问题