In a previous post I discussed the usefulness of implementing IComparable for your classes to assist in sorting your custom objects in ArrayLists. When you call Sort() on the ArrayList, the default implementation of IComparer is called which uses QuickSort. QuickSort calls the IComparable implementation of CompareTo() on each of your objects in the ArrayList.
Sometime this isn’t enough and you will want to pass in your own IComparer for more flexibility, such as to allow you to specify by which field you want to sort the custom objects in the ArrayList.
Rather than calling the Sort() method on the ArrayList and using the default IComparer, we are going to use an overloaded method of the ArrayList Sort method which allows us to pass in our own IComparer:
In keeping with the same People ArrayList and Person Class we have been using in our examples, here is our custom PersonComparer Class that implements IComparer for use in our custom sorting:
The class itself won’t be doing any comparisons. It only keeps track of which field you want to compare by and delegates the comparison to the Person class itself by calling an overloaded method of CompareTo implemented by Person:
And, of course, as shown above, the overloaded version of CompareTo just delegates the comparison right back to the String and Int32 classes, which implement IComparable.
Here is the complete code listing that you can run in Snippet Compiler. It essentially sorts the People ArrayList 3 different times by Lastname, Age, and Firstname, respectively.
Now we have a way to sort our custom objects in multiple ways using the custom PersonComparer class. Check out all my Back to Basics Articles.