nomadsoftware |
|
I’ve recently created a program which sorts collections of custom types quite extensively and I thought i’d share the standard method of doing this. When I first started designing my program, I honestly thought it would be quite a pain sorting these collections but I was pleasantly surprised, as usual by the .NET framework, that there are built in shortcuts.
The first stage to allow a custom type to be sorted is to implement the IComparable interface. This consists of one method CompareTo<T>
where T is your custom type. This becomes your default comparer.
Here’s an example:
Once that method is implemented (here we’ve implemented it using the name field to compare against) you can use the native sort methods on a collection of such types and have them sorted via this default comparer. For example if you are using an array as your collection, you can use the default static ‘Sort’ method to sort it:
If you are using a generic list you can use the built in ‘Sort’ method:
Again this uses the default comparer and sorts the collection by the name field.
If you need to give the user the option of multiple ways of sorting your collection you must implement other comparers. This is achieved by implementing Comparison delegates. Let’s implement some in our custom type to allow sorting of every field:
Here, as well as the default comparer, we have implemented three Comparison delegates to provide the rules of sorting the three fields in the custom type. They have been made static so you can use them without referring to an instance of the custom type.
Here is an example of sorting an array of our custom type by the Age field.
and here is how you sort a generic list collection by the Age field:
Simple.
Hopefully this gives you good grounding on sorting custom type collections and although there are other ways of sorting available in the .NET framework, these are the most common.