How to sort collections of custom types in C#

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.

IComparable

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.

Comparison

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.

Submit a comment

1 Comment

  1. Exactly what I was looking for. Thank you!

Submit a Comment

We would love to hear your thoughts. Feel free to submit a comment and join the conversation!

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">