Comparisons and Sorts Within Collections

The System.Collections classes perform comparisons in almost all the processes involved in managing collections, whether searching for the element to remove or returning the value of a key-and-value pair.

Two constructs are used for comparisons. The Equals method, either inherited or derived from Object, simply returns a Boolean to indicate whether two objects are equal. The IComparable.CompareTo method and the IComparer.Compare method return an integer that indicates how the two values compare in relation to each other. Equals is used for equality checks; the IComparable.CompareTo and IComparer.Compare methods and their counterparts on the generic interfaces, the IComparer<T>.Compare and IComparable<T>.CompareTo methods, are used for sorting.

The comparisons can be between elements of the collection, or between an element and a specified value. When comparers are not explicitly specified, at least one of the objects being compared is expected to implement the IComparable interface and be able to compare itself with the other object.

Some classes have methods that accept an IComparer implementation as a parameter. When those methods are used and the IComparer parameter is not a null reference (Nothing in Visual Basic), the objects being compared are not required to implement IComparable themselves. However, it is always a good practice to implement IComparable on all classes that can be used as values in a list collection or as keys in a dictionary collection.

Some constructor overloads for dictionary collections accept an IComparer implementation, which is used to compare keys whenever comparisons are required. Array has overloads of its Sort method that accept an IComparer implementation, which is used only for that specific call to the Sort method.

The current culture setting of the system can affect the comparisons and sorts within a collection. By default, the comparisons and sorts in the Collections classes are culture-sensitive. To ignore the culture setting and therefore obtain consistent comparison and sorting results, use the InvariantCulture with member overloads that accept a CultureInfo. For more information, see Performing Culture-Insensitive String Operations in Collections and Performing Culture-Insensitive String Operations in Arrays.

See Also






Other Resources

Creating and Manipulating Collections