Sorting an Array Using an Independent Comparer Method

Instead of extending a type to implement IComparable to allow sorting, you can create a separate class that knows how to compare objects of that type and use the new class to do the sorting.
Here’s an example of sorting objects of type Person using a custom Compare method.  To start with, we define a new class that implements IComparer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class PersonSorter : IComparer
{
    public int Compare(object o1, object o2)
    {
        Person p1 = o1 as Person;
        Person p2 = o2 as Person;
 
        // Sort by LastName, then by FirstName (ignore case)
        int compare = p1.LastName.ToLower().CompareTo(p2.LastName.ToLower());
        if (compare == 0)
            compare = p1.FirstName.ToLower().CompareTo(p2.FirstName.ToLower());
 
        return compare;
    }
}
Now we can sort using this compare function by passing an instance of the IComparer class into the Sort method.


1
2
3
4
5
6
7
Person[] folks = new Person[4];
folks[0] = new Person("Bronte", "Emily");
folks[1] = new Person("Bronte", "Charlotte");
folks[2] = new Person("Tennyson", "Alfred");
folks[3] = new Person("Mailer", "Norman");
 
Array.Sort(folks, new PersonSorter());