Implementing IComparer

When you call Sort( ) on
the List, the default implementation of IComparer
is called, which uses QuickSort to call the
IComparable implementation of
CompareTo() on each element in the
List.

You are free to create your own implementation of
IComparer, which you might want to do if you need
control over how the sort ordering is defined. In the next example,
you will add a second field to Employee,
yearsOfSvc. You want to be able to sort the
Employee objects in the List on
either field, empID or
yearsOfSvc.

To accomplish this, create a custom implementation of
IComparer, which you pass to the
Sort() method of the List. This
IComparer class,
EmployeeComparer, knows about
Employee objects and knows how to sort them.

EmployeeComparer has the
WhichComparison property, of type
Employee. EmployeeComparer.ComparisonType:

The complete source for this example is shown in Example 9-15. The integer array has been removed to
simplify the example, and the output of the
employee's ToString( ) method has
been enhanced to enable you to see the effects of the sort.

The first block of output shows the
Employee objects as they are added to the
List. The employee ID values and the years of
service are in random order. The second block shows the results of
sorting by the employee ID, and the third block shows the results of
sorting by years of service.

TIP:
If you are
creating
your own collection, as in Example 9-11, and wish to
implement IComparer, you may need to ensure that
all the types placed in the list implement
IComparer (so that they may be sorted), by using
constraints as described earlier.