#135 – Implementing IComparable to Allow Sorting a Custom Type
October 30, 2010 2 Comments
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
Pingback: #138 – Searching a Sorted Array « 2,000 Things You Should Know About C#
Pingback: #137 – Sorting an Array Using an Independent Comparer Method « 2,000 Things You Should Know About C#