Secondary Sort using IComparer

J

Jason Daley

In the following example, does anyone know if and/or how you would do a
secondary sort?

' ******************************
' Usage
' ******************************
Dim alPeople as New Arraylist

alPeople.Add(New objPerson("John","Doe"))
alPeople.Add(New objPerson("Jane","Doe"))
alPeople.Add(New objPerson("Adam","Smith"))

alPeople.Sort(New objPerson.LastNameComparer)

' ******************************
' Class
' ******************************
Public Class objPerson
Private _fname As String
Private _lname As String

Public Sub New()
'noop
End Sub

Public Sub New(fname as String, lname as String)
Me.New()
Me._fname = fname
Me._lname = lname
End Sub

Public Property FirstName() As String
Get
Return _fname
End Get
Set(ByVal Value As String)
_fname = Value
End Set
End Property

Public Property LastName() As String
Get
Return _lname
End Get
Set(ByVal Value As String)
_lname = Value
End Set
End Property

Public Class LastNameComparer
Implements IComparer
Public Function Compare( _
ByVal x As Object, _
ByVal y As Object) As Integer _
Implements System.Collections.IComparer.Compare
Dim lname1, lname2 As String
lname1 = CType(x, objPerson).LastName
lname2 = CType(y, objPerson).LastName
Return lname1.CompareTo(lname2)
End Function
End Class
End Class

My class is more complex than this basic example, but using this
example, how would you sort secondarily on FirstName if LastName's are
the same?

In other words, Jane Doe would be before John Doe if I could sort by
LastName, FirstName sequence.

Is their a cleaner way to do this without concatenating the values
yourself such as this?

' ******************************
Public Class LastNameFirstNameComparer
Implements IComparer
Public Function Compare( _
ByVal x As Object, _
ByVal y As Object) As Integer _
Implements System.Collections.IComparer.Compare
Dim val1, val2 As String
val1 = CType(x, objPerson).LastName & ", " & _
CType(x, objPerson).FirstName
val2 = CType(y, objPerson).LastName & ", " & _
CType(y, objPerson).FirstName
Return val1.CompareTo(val2)
End Function
End Class
' ******************************

Thanks,

Jason
 
J

Jon Skeet [C# MVP]

Jason Daley said:
In the following example, does anyone know if and/or how you would do a
secondary sort?

Use an IComparer that compares both parts - if the primary parts are
equal, move on and compare the secondary parts. An elegant way to do
this is to have an IComparer which contains other IComparers, and calls
them in turn when it's asked to compare two objects.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top