I would like an extension of a question previously posted here
Sort a List of Object in VB.NET
In that question, the OP is asking how to sort a list of objects in VB.NET.
His example uses something like
And then, the accepted answer uses
theList.Sort(Function(x, y) x.age.CompareTo(y.age))
To that point, everything is ok.
My extension to this is to ask what happens if, for example, I am sorting by age, like the example, however, let's say that 2 passengers have the same age, then, in that case, I would like to use a second parameter (let's say
passenger.name), to sort.
Could it be done using the same
Best How To :
You could implement a custom
IComparer(Of Passenger) for
Implements IComparer(Of Passenger)
Public Function Compare(p1 As Passenger, p2 As Passenger) As Integer Implements System.Collections.Generic.IComparer(Of Passenger).Compare
If p1.Age = p2.Age AndAlso p1.Name = p2.Name Then
ElseIf p1.Age <> p2.Age Then
ElseIf p1.Name <> p2.Name Then
Now you can use this:
Another way is to use LINQ:
Dim ordered = From obj In theList
OrderBy obj.Age Ascending, obj.Name Ascending
theList = ordered.ToList()