Custom Sorting ArrayLists

A co-worker approached me with the problem of sorting an ArrayList of ArrayLists. Normally you might handle this in a DataTable or entity collection in your particular ORM. In this case, this was the data structure that was available to sort:


Knowing a little bit about how ORM tools work, I made the guess that they implement a custom comparer to perform this functionality, so I took a look at what it would take for this instance.

This turned out to be a lot easier than I thought, you need to create a class that implements IComparer and pass an instance of that class to the Sort method of the ArrayList.

public class CustomArrayListComparer : IComparer {
    int IComparer.Compare(object x, object y) {
        return ((int)((ArrayList)x)[0]).CompareTo((int)(ArrayList)y))[0]);

// example:
myArrayList.Sort(new CustomArrayListComparer());

I know that the above code looks somewhat unreadable, but for the sake of the efficiency of the sort operation, all casting is done in place. It’s necessary to cast objects x and y to an ArrayList in order to access their collection of objects. Since we know that, in this case, the 0th item in the ArrayList is an int, that is cast to an int and the Int32.CompareTo() method is used.