C# IComparer
last modified November 6, 2026
In this article we show how to compare values in C# with the
IComparer interface.
Unlike simple types such as numbers and strings, more complex types do not
have an intrinsic ordering. We have to define the ordering ourselves. In C#, we
can use for this task the Comparison delegate, the
IComparer and IComparable interfaces, or LINQ.
C# IComparer interface
The IComparer<T> interface defines a method that compares
two objects. Unlike IComparable, it is implemented by a separate
class, not by the compared type itself.
This interface is used with the List.Sort,
Array.Sort, and List.BinarySearch methods, with
LINQ's Order and OrderBy, and with sorted collections.
It provides a way to customize the sort order of a collection.
SortedDictionary, SortedList, and
SortedSet accept a comparer in their constructors.
int Compare(T? x, T? y)
The Compare method compares two objects and returns a negative
number, zero, or a positive number, depending on whether the first object is
less than, equal to, or greater than the second one.
The interface is used for types that we do not have control over; in other words, for code that we have not written. If the code is developed by ourselves, we can use the IComparable interface instead.
With IComparer we have more flexibility; we can define multiple
comparers or update existing ones without touching the type itself. Also, it
has a cleaner design, since we separate the sorting implementation from the
type.
C# IComparer example
In the following example, we sort a list of employees.
List<(string Name, int Salary)> employees =
[
("John Doe", 1230),
("Adam Novak", 670),
("Robin Brown", 2300),
("Rowan Cruise", 990),
("Joe Draker", 1190),
("Janet Doe", 980),
("Thomas Moore", 1400)
];
employees.Sort(new SalaryComparer());
employees.ForEach(employee => Console.WriteLine(employee));
class SalaryComparer : IComparer<(string Name, int Salary)>
{
public int Compare((string Name, int Salary) emp1, (string Name, int Salary) emp2)
{
return emp1.Salary.CompareTo(emp2.Salary);
}
}
In the example, we provide an implementation of the Compare
method in the SalaryComparer. The employees are represented by
named tuples.
public int Compare((string Name, int Salary) emp1, (string Name, int Salary) emp2)
{
return emp1.Salary.CompareTo(emp2.Salary);
}
The implementation of the Compare method sorts the employees by
their salary.
employees.Sort(new SalaryComparer());
We sort the list. The method takes the implemented Compare
method into account when sorting.
$ dotnet run (Adam Novak, 670) (Janet Doe, 980) (Rowan Cruise, 990) (Joe Draker, 1190) (John Doe, 1230) (Thomas Moore, 1400) (Robin Brown, 2300)
C# IComparer with null values
In the following example, we sort an array of users, which contains a null element.
User?[] users =
[
new("Robin", "bookseller"),
new("John", "gardener"),
null,
new("John", "writer"),
new("Janet", "teacher"),
new("Andrew", "driver"),
new("Lucy", "accountant")
];
Array.Sort(users, new OccupationComparer());
foreach (var user in users)
{
Console.WriteLine(user?.ToString() ?? "null");
}
record User(string Name, string Occupation);
class OccupationComparer : IComparer<User?>
{
public int Compare(User? u1, User? u2)
{
if (u1 is null && u2 is null) return 0;
if (u1 is null) return -1;
if (u2 is null) return 1;
return string.Compare(u1.Occupation, u2.Occupation, StringComparison.Ordinal);
}
}
The example sorts an array of users in ascending order. To create objects, we use records.
public int Compare(User? u1, User? u2)
{
if (u1 is null && u2 is null) return 0;
if (u1 is null) return -1;
if (u2 is null) return 1;
return string.Compare(u1.Occupation, u2.Occupation, StringComparison.Ordinal);
}
The method sorts by the occupation. By convention, non-null objects are greater than nulls, so the null element comes first.
Array.Sort(users, new OccupationComparer());
We pass the comparer to the Array.Sort method.
$ dotnet run
null
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 }
C# IComparer multiple fields
In the following example, we compare by two fields.
List<User> users =
[
new("Robin", "bookseller"),
new("Simon", "teacher"),
new("Arnold", "teacher"),
new("John", "gardener"),
new("Adam", "gardener"),
new("Peter", "gardener"),
new("John", "writer"),
new("Janet", "teacher"),
new("Andrew", "driver"),
new("Lucy", "accountant"),
new("Michael", "teacher")
];
users.Sort(new OccupationNameReverseComparer());
foreach (var user in users)
{
Console.WriteLine(user);
}
record User(string Name, string Occupation);
class OccupationNameReverseComparer : IComparer<User>
{
public int Compare(User? u1, User? u2)
{
if (u1 is null && u2 is null) return 0;
if (u1 is null) return -1;
if (u2 is null) return 1;
int res = string.Compare(u1.Occupation, u2.Occupation, StringComparison.Ordinal);
if (res == 0)
{
res = string.Compare(u2.Name, u1.Name, StringComparison.Ordinal);
}
return res;
}
}
We have users with the same occupation. In such a case, we then compare their names.
int res = string.Compare(u1.Occupation, u2.Occupation, StringComparison.Ordinal);
if (res == 0)
{
res = string.Compare(u2.Name, u1.Name, StringComparison.Ordinal);
}
First, we compare users by their Occupation fields. If they are
equal, we compare their Name fields. Since the arguments of the
second comparison are swapped, the names are sorted in descending 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 }
C# Comparer.Create and Comparison delegate
Writing a class for each comparer is verbose. The
Comparer<T>.Create method creates a comparer from a lambda
expression. The sort methods also accept a Comparison<T>
delegate directly.
List<string> words = ["falcon", "sky", "by", "water", "atom", "forest", "owl"];
var byLength = Comparer<string>.Create((a, b) => a.Length.CompareTo(b.Length));
words.Sort(byLength);
Console.WriteLine(string.Join(", ", words));
words.Sort((a, b) => b.Length.CompareTo(a.Length));
Console.WriteLine(string.Join(", ", words));
var reverse = Comparer<string>.Create((a, b) =>
Comparer<string>.Default.Compare(b, a));
words.Sort(reverse);
Console.WriteLine(string.Join(", ", words));
We sort words by their length in three different ways.
var byLength = Comparer<string>.Create((a, b) => a.Length.CompareTo(b.Length));
The Create method wraps the lambda in an
IComparer<string> object, which can be stored and reused.
words.Sort((a, b) => b.Length.CompareTo(a.Length));
Here we pass a Comparison<string> delegate. Swapping the
arguments gives the descending order.
var reverse = Comparer<string>.Create((a, b) =>
Comparer<string>.Default.Compare(b, a));
The Comparer<T>.Default property returns the comparer
which uses the type's IComparable<T> implementation. We use
it to create a comparer for reverse order.
The List.Sort method is not stable. Words of the same length may
end up in any order relative to each other.
$ dotnet run by, sky, owl, atom, water, falcon, forest falcon, forest, water, atom, sky, owl, by water, sky, owl, forest, falcon, by, atom
C# StringComparer
StringComparer is a built-in comparer for comparing strings. It
represents a string comparison operation that uses specific case and
culture-based or ordinal comparison rules.
List<string> words =
[
"sky", "blue", "Church", "cup", "Adam", "also", "Bratislava", "bear", "snow",
"carpet", "water", "volcano", "smell", "forest", "Earth"
];
words.Sort(StringComparer.Ordinal);
Console.WriteLine(string.Join(", ", words));
Console.WriteLine("---------------------");
words.Sort(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(string.Join(", ", words));
A list of words is compared with StringComparer using
Ordinal and OrdinalIgnoreCase rules. The ordinal
comparison compares the numeric values of characters; all uppercase letters
precede lowercase ones.
$ dotnet run Adam, Bratislava, Church, Earth, also, bear, blue, carpet, cup, forest, sky, smell, snow, volcano, water --------------------- Adam, also, bear, blue, Bratislava, carpet, Church, cup, Earth, forest, sky, smell, snow, volcano, water
C# LINQ Order with IComparer
The LINQ's Order and OrderDescending methods have
overloaded variants which take an IComparer as a parameter. So do
OrderBy and ThenBy.
List<string> words = [
"world", "War", "abbot", "Caesar", "castle", "sky", "den",
"forest", "ocean", "water", "falcon", "owl", "rain", "Earth"
];
var sorted = words.Order(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(string.Join(", ", sorted));
Console.WriteLine("-------------------------");
var sorted2 = words.OrderDescending(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(string.Join(", ", sorted2));
Console.WriteLine("-------------------------");
var sorted3 = words.OrderBy(w => w.Length).ThenBy(w => w, StringComparer.Ordinal);
Console.WriteLine(string.Join(", ", sorted3));
In the program, we sort a list of words with Order and
OrderDescending. We pass the
StringComparer.OrdinalIgnoreCase to the methods.
var sorted3 = words.OrderBy(w => w.Length).ThenBy(w => w, StringComparer.Ordinal);
The words are sorted by their length and then alphabetically with the ordinal comparer. LINQ sorting is stable and does not modify the source list.
$ dotnet run abbot, Caesar, castle, den, Earth, falcon, forest, ocean, owl, rain, sky, War, water, world ------------------------- world, water, War, sky, rain, owl, ocean, forest, falcon, Earth, den, castle, Caesar, abbot ------------------------- War, den, owl, sky, rain, Earth, abbot, ocean, water, world, Caesar, castle, falcon, forest
C# IComparer in sorted collections
Sorted collections use a comparer to keep their elements ordered and to find keys.
var comparer = StringComparer.OrdinalIgnoreCase;
var stock = new SortedDictionary<string, int>(comparer)
{
["pears"] = 4,
["Apples"] = 12,
["bananas"] = 7
};
stock["APPLES"] += 3;
foreach (var (fruit, n) in stock)
{
Console.WriteLine($"{fruit}: {n}");
}
var descending = Comparer<int>.Create((a, b) => b.CompareTo(a));
var scores = new SortedSet<int>([45, 78, 12, 99, 61], descending);
Console.WriteLine(string.Join(", ", scores));
We create a case-insensitive SortedDictionary and a
SortedSet with descending order.
stock["APPLES"] += 3;
Since the dictionary uses a case-insensitive comparer, the
APPLES key refers to the existing Apples entry.
var scores = new SortedSet<int>([45, 78, 12, 99, 61], descending);
The set keeps the scores from the highest to the lowest.
$ dotnet run Apples: 15 bananas: 7 pears: 4 99, 78, 61, 45, 12
C# IComparer and BinarySearch
The BinarySearch method finds an element in a sorted list in
O(log n) time. The list must be sorted with the same comparer that is
used for the search.
List<string> words = ["Atom", "blue", "Cup", "dog", "Earth", "forest"];
var comparer = StringComparer.OrdinalIgnoreCase;
words.Sort(comparer);
int idx = words.BinarySearch("CUP", comparer);
Console.WriteLine($"CUP found at index {idx}");
int idx2 = words.BinarySearch("cat", comparer);
Console.WriteLine($"cat not found: {idx2}");
words.Insert(~idx2, "cat");
Console.WriteLine(string.Join(", ", words));
We sort the words case-insensitively and search them with the same comparer.
int idx2 = words.BinarySearch("cat", comparer);
If the element is not found, the method returns a negative number. It is the bitwise complement of the index at which the element should be inserted.
words.Insert(~idx2, "cat");
We insert the word at the correct position, so the list stays sorted.
$ dotnet run CUP found at index 2 cat not found: -3 Atom, blue, cat, Cup, dog, Earth, forest
Source
In this article we have used the IComparer interface to sort data
in C#.
Author
List all C# tutorials.