Sort descending using IComparable ?

  • Thread starter Thread starter John Devlon
  • Start date Start date
J

John Devlon

Hi everyone,

With this post I would like to ask you all a small question.

I'm trying to sort an array of objects using IComparable. Adding below
displayed code to a class and triggering the sort function works fine. Thats
not the problem.

The only thing I would like to change is: I would like sort the Name
descending (starting with the z)...
Does anyone know how ?

Many Thanx

John

Ps: using VB.NET 2005


Code:

Public Function CompareTo(ByVal myPerson As clsPerson) As Integer Implements
System.IComparable(Of clsPerson).CompareTo
If Me.Language = myPerson.Language Then
If Me.City = myPerson.City Then
Return Me.Name.CompareTo(myPerson.Name)
Else
Return Me.City.CompareTo(myPerson.City)
End If
Else
Return Me.Language.CompareTo(myPerson.Language)
End If

End Function
 
John Devlon said:
Hi everyone,

With this post I would like to ask you all a small question.

I'm trying to sort an array of objects using IComparable. Adding below
displayed code to a class and triggering the sort function works fine.
Thats not the problem.

The only thing I would like to change is: I would like sort the Name
descending (starting with the z)...
Does anyone know how ?

The link talks about Array.Sort and then Array.Reverse.

http://samples.gotdotnet.com/quickstart/howto/doc/sort.aspx

The link talks about Key/Item pairs sorting.

http://msdn2.microsoft.com/en-us/library/system.array.sort(vs.80).aspx
 
Hello,

Just return the opposite sign of the comparison.

Public Function CompareTo(ByVal myPerson As clsPerson) As Integer
Implements System.IComparable(Of clsPerson).CompareTo
Dim result As Integer

If Me.Language = myPerson.Language Then
If Me.City = myPerson.City Then
result = Me.Name.CompareTo(myPerson.Name)
Else
result = Me.City.CompareTo(myPerson.City)
End If
Else
result = Me.Language.CompareTo(myPerson.Language)
End If

Return -result ' return opposite
End Function
 
Hello again,

I replied to quickly without realizing you only wanted to change the
sorting order of the Name property. Just return the opposite for the
Name comparison only.

Public Function CompareTo(ByVal myPerson As clsPerson) As Integer
Implements System.IComparable(Of clsPerson).CompareTo
If Me.Language = myPerson.Language Then
If Me.City = myPerson.City Then
Return -Me.Name.CompareTo(myPerson.Name) ' return opposite
Else
Return Me.City.CompareTo(myPerson.City)
End If
Else
Return Me.Language.CompareTo(myPerson.Language)
End If
End Function
 
Dear Ms Ethridge,

Your absolutely amazing. It works perfect. Your the best.
How can I ever repay you ?

Kind regards,

John
 
Back
Top