C# Interview Question #127

What is an IComparer<T> in C#?

Advanced LINQ, Expressions & Collections Senior Advanced

Quick Interview Answer

IComparer<T> defines custom ordering logic through the Compare method. It is useful when objects need to be sorted using a rule that is separate from the object's natural ordering.

Detailed Explanation

IComparer<T> defines custom ordering logic through the Compare method. It is useful when objects need to be sorted using a rule that is separate from the object's natural ordering.

For example, products can be sorted by price, rating, title, or another business rule without modifying the Product class.

Comparer<T>.Create can also create a comparer from a lambda expression.

Code Example

var comparer = Comparer<Product>.Create(
    (a, b) => a.Price.CompareTo(b.Price));

products.Sort(comparer);