vb.netsortinglistof

Sorting list of by their X and Y property


I have a list of "clsLabel":

Private _ListOfAllLabels As New List(Of clsLabel)

Public Class clsLabel
    Public Name As String
    Public X As Double
    Public Y As Double
End Class

X and Y define the location of the Label.

How could I sort my List(of clsLabel) in such a way that it's sorted by Y and then by X ascendingly?

Thank you!


Solution

  • The List(Of T) class has its own Sort method that will sort in-place. It allows you to use an IComparer(Of T), which you should if you want to do lots of sorting and especially if you want it to be configurable. For a one-off sort though, just use the overload that accepts a Comparison(Of T) delegate:

    _ListOfAllLabels.Sort(Function(l1, l2)
                              Dim result = l1.Y.CompareTo(l2.Y)
    
                              If result = 0 Then
                                  result = l1.X.CompareTo(l2.X)
                              End If
    
                              Return result
                          End Function)
    

    In .NET, sorting is done by defining a comparison between two objects of a type and then performing that comparison repeatedly on pairs of list items based on an algorithm. The comparison should return an Integer value less than 1 if the first item should precede the second, a value greater than 1 if the second item should precede the first and zero if they are equivalent. Types that implement the IComparable/IComparable(Of T) inreface(s), which includes all the VB fundamental types, have such a comparison built in, which is what the CompareTo method used above is.

    If you would like to learn more about .NET sorting, I've created a multi-part blog post on the subject here.