C# IComparable

Sorted letters: A to Z

IComparable allows custom sorting of objects when implemented. When a class implements this interface, we must add the public method CompareTo(T). We implement custom sorting for a class with IComparable.

Interface

Example

Interface

Please look at the Employee class. This class implements IComparable<Employee>, which means an Employee instance can be compared with other Employee instances. The Employee class has two instance properties: Salary and Name.

Also:The Employee class provides the CompareTo(Employee) method and the ToString method.

Program that implements IComparable interface: C#

using System;
using System.Collections.Generic;

class Employee : IComparable<Employee>
{
    public int Salary { get; set; }
    public string Name { get; set; }

    public int CompareTo(Employee other)
    {
	// Alphabetic sort if salary is equal. [A to Z]
	if (this.Salary == other.Salary)
	{
	    return this.Name.CompareTo(other.Name);
	}
	// Default to salary sort. [High to low]
	return other.Salary.CompareTo(this.Salary);
    }

    public override string ToString()
    {
	// String representation.
	return this.Salary.ToString() + "," + this.Name;
    }
}

class Program
{
    static void Main()
    {
	List<Employee> list = new List<Employee>();
	list.Add(new Employee() { Name = "Steve", Salary = 10000 });
	list.Add(new Employee() { Name = "Janet", Salary = 10000 });
	list.Add(new Employee() { Name = "Andrew", Salary = 10000 });
	list.Add(new Employee() { Name = "Bill", Salary = 500000 });
	list.Add(new Employee() { Name = "Lucy", Salary = 8000 });

	// Uses IComparable.CompareTo()
	list.Sort();

	// Uses Employee.ToString
	foreach (var element in list)
	{
	    Console.WriteLine(element);
	}
    }
}

Output

500000,Bill
10000,Andrew
10000,Janet
10000,Steve
8000,Lucy
Note

CompareTo. Look again at the CompareTo method implementation in the Employee class. The method returns int—this indicates which Employee should be ordered first. In CompareTo, we want to sort by the Salary from highest to lowest.

However:If Salary is equal, we want to sort alphabetically. We check for equal Salary values, and in that case sort alphabetically.

Main method

In the Main method, we create a List of Employee instances. Each Employee has a Name and a Salary specified. Then, we invoke the Sort method on List. This uses the IComparable<Employee> implementation we added.

Result:When this program is run, the Employee instances are sorted first by Salary and then by Name.

List

Reverse sorts

Question and answer

What should you do if you want to sort in reverse order in the CompareTo method? For example, if you want to order the Employee instances from lowest to highest salary, you could simply reverse the order of the CompareTo expression.

Fragment that sorts on Salary: high to low

return other.Salary.CompareTo(this.Salary);

Sorts on Salary: low to high

return this.Salary.CompareTo(other.Salary);

Alternatives

LINQ: language integrated query

There are alternative ways you can sort collections of objects by two properties. The easiest is probably the orderby clause in the query syntax in System.Linq. For more information on this, check out the LINQ page on this site.

LINQ Examples: System.Linq and ExtensionsOrderBy ClausePerformance optimization

CompareTo and IComparable are often faster than LINQ and the orderby clause. The IComparable version reorders the elements in the original list, while the orderby clause will return an IEnumerable that you must copy into a new List.

List type

List. There are other syntax forms available for sorting the List type. You can specify the Comparison delegate in the lambda expression syntax. In this case, you do not need to implement the IComparable interface at all.

Caution:This approach may be less robust and exhibit poorer object-orientation. But in many cases, it is acceptable.

Sort Tuple ListSort List Method

Summary

The C# programming language

Through this example program, we implemented the IComparable<T> interface on a class. Then we demonstrated that the List.Sort method uses this interface to sort an object collection.

Finally:We covered alternative methods of sorting objects and the drawbacks of these methods.


C#: Sort