I have a DTO that I am using to process transactions. To ensure that it is processing in the correct order, I am using iComparable and sorting the List(of T) of the DTO. That works great. However I just got another requirement that the customer wants the output in a different order... is there a way to allow me to have two different sorts for the same object, or do I need to copy the current class, save the output as a new List of that type and sort using the new way for that object? Seems like an awful way to do it, but cannot find anything that allows me to do it.
+2
A:
Here is an example I ripped from a recent project. Works like a charm. Just have to remember to call SORT with the appropriate function. This is outside the scope fo the IComparable interface, so you might want to drop that from your class declaration.
Public Class Purchaser
....
Public Shared Function CompareByGroup( _
ByVal x As Purchaser, ByVal y As Purchaser) As Integer
If x Is Nothing Then
If y Is Nothing Then
' If x is Nothing and y is Nothing, they're equal.
Return 0
Else
' If x is Nothing and y is not Nothing, y is greater.
Return -1
End If
Else
If y Is Nothing Then
' If x is not Nothing and y is Nothing, x is greater.
Return 1
Else
' ...and y is not Nothing, compare by GroupName.
Return x.GroupName.CompareTo(y.GroupName)
End If
End If
End Function
Public Shared Function CompareByName( _
ByVal x As Purchaser, ByVal y As Purchaser) As Integer
... 'you get the idea
End Function
And call them like this...
tempList.Sort(AddressOf Classes.Purchaser.CompareByGroup)
or
tempList.Sort(AddressOf Classes.Purchaser.CompareByName)
Bill
2010-08-17 16:58:14
Perfect thanks, I had my compare routines, but could not for the life of me get the syntax right for the sort.
IPX Ares
2010-08-18 13:46:40
A:
Or you can use linq if you are on .Net 3.5 or above.
dim orderedlistofdtos = (from e in listofdtos order by e.whatever select e).Tolist
chrissie1
2010-08-17 18:34:17