#135 – Implementing IComparable to Allow Sorting a Custom Type

Arrays of elements that belong to a custom type cannot be sorted, unless the type implements the IComparable interface.

To make elements of a custom type sortable, you need to implement IComparable in your type.  IComparable consists of the single method CompareTo, which compares two objects.

Here’s an example of a Person class implementing CompareTo to sort people in LastName/FirstName order:

            public int CompareTo(object obj)
            {
                Person other = obj as Person;
                if (other == null)
                    throw new ArgumentException("Object is not a Person");
                else
                {
                    // Sort by LastName, then by FirstName (ignore case)
                    int compare = this.LastName.ToLower().CompareTo(other.LastName.ToLower());
                    if (compare == 0)
                        compare = this.FirstName.ToLower().CompareTo(other.FirstName.ToLower());

                    return compare;
                }

Here’s an example of sorting an array of Person objects:

            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);    // C. Bronte, E. Bronte, Mailer, Tennyson
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #135 – Implementing IComparable to Allow Sorting a Custom Type

  1. Pingback: #138 – Searching a Sorted Array « 2,000 Things You Should Know About C#

  2. Pingback: #137 – Sorting an Array Using an Independent Comparer Method « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: