0

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?

2 Answers 2

2

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, is it any "non-LINQ" option?
Thanks Tim, of course this passenger and age thing is not my case, but of course I can work with that, lots of thanks.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.