Scott wrote:
Good afternoon,
I would like to mimic the sorting capabilities in Excel where I can sort a
list by up to four properties (columns in excel). I would like to pass a
collection of objects to a function and get a sorted collection back. The
sorting would occur based on the user's selection of up to four properties of
the objects in the collection. The sorting may be requested based on UP TO
four properties but could just as easily happen for one property.
How can I code this functionality? What is this type of sorting called so I
can research an algorithm? Does this code already exist somewhere and I can
borrow it?
Thanks,
Scott
You could make an IComparer for each property, and make them chainable
so that you can combine them in any way you like.
Something like:
Public Class NameComparer
Implements IComparer(Of SomeClass)
Private _next As IComparer(Of SomeClass)
Public Sub NameComparer(next as IComparer(Of SomeClass))
_next = next
End Sub
Public Function Compare(x As SomeClass, y As SomeClass) As Integer
Dim result As Integer = String.Compare(x.Name, y.Name)
' Check if names are equal and if there is a next comparer
If result = 0 AndAlso _next Is Not Nothing Then
' Use the next comparer
result = _next.Compare(x, y)
End If
Return result
End Function
End Class
Now you can create comparers and chain them to sort the list on for
example name, city and phone number (building backwards):
Dim comparer As IComparer = New PhoneComparer(Nothing)
comparer = New CityComparer(comparer)
comparer = New NameComparer(comparer)
theListToSort.Sort(comparer)
--
Göran Andersson
_____
http://www.guffa.com