ZetCode

C# IComparable

last modified March 23, 2021

C# IComparable tutorial shows how to compare values in C# with IComparable interface. C# tutorial is a comprehensive tutorial on C# language.

C# IComparable interface

The IComparable interface defines a generalized type-specific comparison method that a value type or class implements to order or sort its instances.

The IComparable is implemented by types whose values can be ordered or sorted. The interface requires the CompareTo method to be implemented. The implemented method is automatically called by methods such as Array.Sort and ArrayList.Sort.

The interface is used by types that the programmer has control over; in other words by code that he has written. If the code is provided by someone else, we use the IComparer interface instead.

C# IComparable example

In the following example, we sort a list of employees.

Program.cs
using System;
using System.Collections.Generic;

var employees = new List<Employee> 
{
    new Employee("John Doe", 1230),
    new Employee("Lucy Novak", 670),
    new Employee("Robin Brown",2300),
    new Employee("Joe Draker", 1190),
    new Employee("Janet Doe", 980)
};

employees.Sort();
employees.ForEach(employee => Console.WriteLine(employee));

Console.WriteLine("---------------------------");

employees.Reverse();
employees.ForEach(employee => Console.WriteLine(employee));

record Employee(string Name, int Salary) : IComparable<Employee>
{
    public int CompareTo(Employee other)
    {
        // return other.Salary.CompareTo(this.Salary);
        if (this.Salary < other.Salary)
        {
            return 1;
        }
        else if (this.Salary > other.Salary)
        {
            return -1;
        }
        else
        {
            return 0;
        }
    }
}

In the example, we provide an implementation of the CompareTo method of the Employee class. The class implements the IComparable interface.

public int CompareTo(Employee other)
{
    // return other.Salary.CompareTo(this.Salary);
    if (this.Salary < other.Salary)
    {
        return 1;
    }
    else if (this.Salary > other.Salary)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

The implementation of the CompareTo method will sort the employees by their salary.

employees.Sort();

We sort the list. The method takes the implemented CompareTo method into account when sorting.

employees.Reverse();

We sort the list in reverse order.

$ dotnet run
Employee { Name = Robin Brown, Salary = 2300 }
Employee { Name = John Doe, Salary = 1230 }
Employee { Name = Joe Draker, Salary = 1190 }
Employee { Name = Janet Doe, Salary = 980 }
Employee { Name = Lucy Novak, Salary = 670 }
---------------------------
Employee { Name = Lucy Novak, Salary = 670 }
Employee { Name = Janet Doe, Salary = 980 }
Employee { Name = Joe Draker, Salary = 1190 }
Employee { Name = John Doe, Salary = 1230 }
Employee { Name = Robin Brown, Salary = 2300 }

C# IComparable example II

In the following example, we sort an array of users.

Program.cs
using System;

var users = new User[] 
{
    new User("Robin", "bookseller"),
    new User("John", "gardener"),
    new User("John", "writer"),
    new User("Janet", "teacher"),
    new User("Andrew", "driver"),
    new User("Lucy", "accountant")
};

Array.Sort(users);

foreach (var user in users)
{
    Console.WriteLine(user);
}

Console.WriteLine("------------------------------");

Array.Reverse(users);

foreach (var user in users)
{
    Console.WriteLine(user);
}

record User(string Name, string Occupation) : IComparable<User>
{
    public int CompareTo(User other)
    {
        return this.Occupation.CompareTo(other.Occupation);
    }
}

The example sorts an array of users in ascending and descending order.

public int CompareTo(User other)
{
    return this.Occupation.CompareTo(other.Occupation);
}

The method sorts by the occupation.

Array.Sort(users);

We sort the users in ascending order.

Array.Reverse(users);

We sort the users in descending order.

$ dotnet run
User { Name = Lucy, Occupation = accountant }
User { Name = Robin, Occupation = bookseller }
User { Name = Andrew, Occupation = driver }
User { Name = John, Occupation = gardener }
User { Name = Janet, Occupation = teacher }
User { Name = John, Occupation = writer }
------------------------------
User { name = John, Occupation = writer }
User { name = Janet, Occupation = teacher }
User { name = John, Occupation = gardener }
User { name = Andrew, Occupation = driver }
User { name = Robin, Occupation = bookseller }
User { name = Lucy, Occupation = accountant }

C# IComparable multiple fields

In the following example, we compare by two fields.

Program.cs
using System;
using System.Collections.Generic;

var users = new List<User> 
{
    new User("Robin", "bookseller"),
    new User("Simon", "teacher"),
    new User("Arnold", "teacher"),
    new User("John", "gardener"),
    new User("Adam", "gardener"),
    new User("Peter", "gardener"),
    new User("John", "writer"),
    new User("Janet", "teacher"),
    new User("Andrew", "driver"),
    new User("Lucy", "accountant"),
    new User("Michael", "teacher")
};

users.Sort();

foreach (var user in users)
{
    Console.WriteLine(user);
}

record User(string Name, string Occupation) : IComparable<User>
{
    public int CompareTo(User other)
    {
        int res = this.Occupation.CompareTo(other.Occupation);

        if (res == 0) 
        {
            res = other.Name.CompareTo(this.Name);
        }

        return res;
    }
}

We have users with the same occupation. In such a case, we then compare their names.

public int CompareTo(User other)
{
    int res = this.Occupation.CompareTo(other.Occupation);

    if (res == 0) 
    {
        res = other.Name.CompareTo(this.Name);
    }

    return res;
}

First, we compare users by their Occupation fields. If they are equal, we compare their Name fields. The way we compare the names result in descending sorting order.

$ dotnet run 
User { Name = Lucy, Occupation = accountant }
User { Name = Robin, Occupation = bookseller }
User { Name = Andrew, Occupation = driver }
User { Name = Peter, Occupation = gardener }
User { Name = John, Occupation = gardener }
User { Name = Adam, Occupation = gardener }
User { Name = Simon, Occupation = teacher }
User { Name = Michael, Occupation = teacher }
User { Name = Janet, Occupation = teacher }
User { Name = Arnold, Occupation = teacher }
User { Name = John, Occupation = writer }

In this tutorial, we have used IComparable interface to sort data in C#.

Read C# tutorial or list all C# tutorials.