Implementing the IComparable interface enables you to choose the way an enumerable is ordered. For example:

public class Person : IComparable
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }

    public int CompareTo(object obj)
    {
        var person = obj as Person;

        if (person == null)
        {
            return -1;
        }

        return Address.CompareTo(person.Address);
    }
}

Using the class we created above; we can create a list and see the results after the ordering:

var person1 = new Person
{
    Id = 1,
    Name = "John",
    Address = "Williams 24"
};

var person2 = new Person
{
    Id = 2,
    Name = "Aaron",
    Address = "Baron 22"
};

var person3 = new Person
{
    Id = 3,
    Name = "Bob",
    Address = "Arena 4"
};

var people = new Person[] { person1, person2, person3 };
Array.Sort(people);
Console.WriteLine(people[0].Name);
//Bob will be printed

As we can see this interface can help us use a custom way to sort our collections. This is a really nice way to avoid re-allocating a new array and alter the original one to save memory and have a better performance.

Leave a comment

Trending