#137 – 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.

        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.

            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());
Advertisements