Many of the collection types in System.Collections implement a Sort() method that can be used to sort data in a (mostly) arbitrary way. I say mostly in this case because an inconsistent comparison may lead to an ArgumentException.
There are a few basic rules to remember. Given a Comparison or IComparer that compares objects x (the first argument) and y (the second argument), the following may happen:
- If the comparison returns -1 (or any value less than 0), object x will be placed before y.
- If the comparison returns 0, object x and y will retain their positions.
- If the comparison returns 1 (or any value greater than 0), object y will be placed before object x.
Since the integer types implement the IComparable interface, these examples can be written more compactly as:
return -1 * x.CompareTo(y);
It should be noted that if a collection contains objects that do not implement IComparable, the Sort() method will throw an InvalidOperationException unless a custom Comparison delegate or implementation of IComparer is used. People often run into this with List<T> and ArrayList<T>, among other specialized types.
Up until now, I've demonstrated using a System.Comparison delegate with the Sort() method. Here is an example of a class that implements IComparer and its use in a corresponding Sort() operation:
As a general pattern, the delegate form makes the most sense in simple code that is not expected to be reused (potentially with the transaction script pattern) because it is potentially difficult to modify if it becomes spread across multiple locations. More complex code (think object composition and more complex design patterns) or code that requires the ability to define a sort at runtime should implement IComparer in a different class that can be reused and centrally modified as necessary.
In the next set of examples, I'll look at more complex sorting scenarios.