score:0

Try

Public Class PeopleComparer
    Implements IComparer(Of People)

    Public Function Compare(x As People, y As People) As Integer
         Dim lnameComparison As Integer = x.LName.CompareTo(y.LName)
         Return If(lnameComparison = 0, x.FName.CompareTo(y.FName), lnameComparison)
    End Function
End Class

and

lstPeople.Sort(New PeopleComparer())

score:1

Is this possible?

Yes, just write a comparer that implements the ordering that you want. So compare the last name first; if they are not equal return the result of CompareTo and if they are not equal return the comparison between the first names.

score:1

Yeah it's possible. I think the best way, if you can change the "People" class, create you own CompareTo() function.

Private Function CompareTo(p2 As People) As Integer
    Dim i As Int32 = Me.LName.CompareTo(p2.LName)
    If i = 0 Then
        Return Me.FName.CompareTo(p2.FName)
    End If
    Return i
End Function

then use it :

  lstPeople.Sort(Function(p1, p2) p1.CompareTo(p2))   

EDIT : Convert to VB.NET.

score:0

Implements System.Collections.Generic.IComparer(Of People).Compare have to be added to the function. Stub is generated by typing enter key after IComparer(Of People)

Public Class PeopleComparer
    Implements IComparer(Of People)

    Public Function Compare(x As People, y As People) As Integer Implements System.Collections.Generic.IComparer(Of People).Compare
        Dim lnameComparison As Integer = x.LName.CompareTo(y.LName)
        Return If(lnameComparison = 0, x.FName.CompareTo(y.FName), lnameComparison)
    End Function
End Class

score:0

Bala R's answer is essentially correct, but I had to provide the compiler with a little more information to get past the compiler error you were seeing:

Public Class PeopleComparer
    Implements IComparer(Of People)

    Public Function Compare(x As People, y As People) As Integer Implements IComparer(Of People).Compare
         Dim lnameComparison As Integer = x.LName.CompareTo(y.LName)
         Return If(lnameComparison = 0, x.FName.CompareTo(y.FName), lnameComparison)
    End Function
End Class

and

lstPeople.Sort(New PeopleComparer())

Related Articles