codeKiller
codeKiller

Reputation: 5758

sort list of objects in VB.NET by two elements

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

passenger.name
passenger.age
passenger.surname

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 theList.Sort expression?

Upvotes: 0

Views: 3304

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460288

You could implement a custom IComparer(Of Passenger) for List.Sort:

Class PassengerComparer
    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
            Return 0
        ElseIf p1.Age <> p2.Age Then
            Return p1.Age.CompareTo(p2.Age)
        ElseIf p1.Name <> p2.Name Then
            Return p1.Name.CompareTo(p2.Name)
        End If
    End Function
End Class

Now you can use this:

list.Sort(New PassengerComparer())

Another way is to use LINQ:

Dim ordered = From obj In theList
              OrderBy obj.Age Ascending, obj.Name Ascending
theList = ordered.ToList()

Upvotes: 2

Sonorpearl
Sonorpearl

Reputation: 57

If I remember corretly it should be done by:

theList = theList.OrderBy(Function(x, y) x.age.CompareTo(y.age)).ThenBy(Function(x) x.name) ' .toList()

Upvotes: 2

Related Questions