Sorting by multiple properties

S

Scott

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
 
G

Göran Andersson

Scott said:
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)
 
C

Cor Ligthert[MVP]

Scott,

As you compare this with an excel sheet, then I assume you are talking about
a kind of data.

In a datatable you can sort in any direction you want, like the same you can
do in Linq for if fact everything.

Cor
 

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