0Pricing
C# Academy · Lesson

IComparer for Custom Sorting

Provide alternate orderings with comparers.

Sorting Different Ways

A type has only one natural order via IComparable<T>. To sort the same data in other ways, supply an IComparer<T> or a Comparison<T> delegate at the call site.

Implementing IComparer<T>

An IComparer<T> is a separate object with a Compare(x, y) method. It follows the same negative/zero/positive contract as CompareTo.

using System;
using System.Collections.Generic;

public class Person
{
    public string Name;
    public int Age;
    public Person(string name, int age) { Name = name; Age = age; }
    public override string ToString() => Name + "(" + Age + ")";
}

public class ByName : IComparer<Person>
{
    public int Compare(Person x, Person y)
        => string.Compare(x.Name, y.Name, StringComparison.Ordinal);
}

public class Program
{
    public static void Main()
    {
        var people = new List<Person> { new Person("Zoe", 1), new Person("Ann", 2) };
        people.Sort(new ByName());
        Console.WriteLine(string.Join(", ", people));
    }
}

All lessons in this course

  1. Implementing IEquatable
  2. Overriding GetHashCode
  3. Implementing IComparable
  4. IComparer for Custom Sorting
← Back to C# Academy