IComparer Interface
Namespace: System.Collections
Assembly: System.dll
public interface IComparer
Description
Provides a generalized comparison contract that defines a single method for comparing two objects. This interface is used to create custom comparers for sorting or maintaining the order of collections.
Members
Methods
int Compare(object x, object y)
Parameters
-
xThe first object to compare. -
yThe second object to compare.
Returns
-
intA signed integer that indicates the relative order of the objects being compared.- Less than zero:
xis less thany. - Zero:
xis equal toy. - Greater than zero:
xis greater thany.
- Less than zero:
Remarks
The Compare method is used by sorting algorithms and data structures that require ordering. For example, the Array.Sort(Array, IComparer) method uses this interface to sort an array of objects. When implementing IComparer, you should ensure that the comparison is transitive (if a is less than b, and b is less than c, then a must be less than c), symmetric (if a is equal to b, then b is equal to a), and reflexive (a is equal to a).
Example
The following example demonstrates how to implement the IComparer interface to sort a collection of strings by their length.
using System;
using System.Collections;
using System.Collections.Generic;
public class StringLengthComparer : IComparer
{
public int Compare(object x, object y)
{
string s1 = x as string;
string s2 = y as string;
if (s1 == null || s2 == null)
{
throw new ArgumentException("Input must be strings.");
}
if (s1.Length < s2.Length)
{
return -1;
}
else if (s1.Length > s2.Length)
{
return 1;
}
else
{
return 0;
}
}
}
public class Example
{
public static void Main(string[] args)
{
string[] words = { "apple", "banana", "kiwi", "orange", "grape" };
Array.Sort(words, new StringLengthComparer());
Console.WriteLine("Sorted by length:");
foreach (string word in words)
{
Console.WriteLine(word);
}
}
}