C# Reference ยท Collections
Comparer<T>.Create() and Comparer<T>.Default
Reference for C# Comparer<T>: build an IComparer<T> from a Comparison lambda with Create(), get the natural order with Default, and combine keys with ThenBy-style logic.
Comparer<T> is an abstract base class that implements both IComparer<T> and the non-generic IComparer. You rarely derive from it. Instead you use two static members: Comparer<T>.Default, the comparer for a type's natural order, and Comparer<T>.Create(Comparison<T>), which wraps a lambda in a comparer object.
That wrapping is useful because many APIs want an IComparer<T> object (a SortedSet<T>, Array.BinarySearch, PriorityQueue), while writing a whole class for a one-line comparison is noisy.
var byLength = Comparer<string>.Create((a, b) => a.Length.CompareTo(b.Length)); var natural = Comparer<int>.Default;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static Comparer<T> Default { get; } public static Comparer<T> Create(Comparison<T> comparison); public abstract int Compare(T? x, T? y);
| Name | Description |
|---|---|
comparison |
A delegate (T x, T y) => int that follows the IComparer<T> contract (negative, zero, positive). |
Returns: Create returns a new comparer that calls your delegate. Default returns a comparer that uses IComparable<T>, falls back to IComparable, and handles null.
Errors: Create throws ArgumentNullException when comparison is null. Default.Compare throws ArgumentException when T implements neither IComparable<T> nor IComparable.
Usage notes
Comparer<T>.Createreturns a comparer that is built on your delegate. It is fine for sorting, but it does not giveSortedSet<T>any hash or equality information: two items that compare as zero are considered duplicates.- To sort descending, swap the arguments (
b.CompareTo(a)). Do not negate the result:-int.MinValueis stillint.MinValue. - For several keys, compare the first key and return it when it is non-zero; compare the next key only on a tie. LINQ
OrderBy(...).ThenBy(...)does the same job with less code. Comparer<string>.Defaultcompares with the current culture, so results can differ between machines. PreferStringComparer.OrdinalorStringComparer.OrdinalIgnoreCaseand say what you mean (see StringComparer).- A delegate that captures variables allocates a closure; if the comparer is created in a hot loop, create it once and reuse it.
Comparer<T>.Defaultis cached per type and thread-safe. A custom comparer is as thread-safe as the lambda you give it.- Do not use a random result or a comparison that changes while sorting: sort algorithms need a consistent order.