
.NET 2.0+Implementing IComparer<T> (2)
The generic IComparer<T> interface was introduced with the .NET framework version 2.0. It is used to compare two values to determine which is the larger. The interface is used in many standard .NET methods, particularly those that sort information.
Creating the Customer Name Comparer
The second comparer will compare two customers based upon their surname and forename. Where the surnames of the customers match, they will be sorted according to the forename. In this case we cannot obtain a result by simple subtraction. We start by using the String class' static Compare method to compare the surnames. String.Compare uses the same principles as the method in the IComparer<T> interface. If the result of the comparison it not zero, we can just return it.
If the comparison of surnames yields a zero result, the surnames match. In this case we must compare the forenames. Again we use String.Compare and simply return the result. The full implementation is shown below.
public class NameComparer : IComparer<Customer>
{
public int Compare(Customer customer1, Customer customer2)
{
int surnameComparison = string.Compare(customer1.Surname, customer2.Surname);
if (surnameComparison == 0)
return string.Compare(customer1.Forename, customer2.Forename);
else
return surnameComparison;
}
}
Testing the Comparers
We can now test the two comparers by creating several Customer objects and comparing them. The code below creates three customers and adds them to an array. The array is sorted using an AnnualSpendComparer. The results are therefore ordered by the annual spend value, as seen in the comment.
Customer customer1 = new Customer();
customer1.Forename = "Jim";
customer1.Surname = "Smith";
customer1.AnnualSpend = 1000;
Customer customer2 = new Customer();
customer2.Forename = "Bob";
customer2.Surname = "Smith";
customer2.AnnualSpend = 2000;
Customer customer3 = new Customer();
customer3.Forename = "Bob";
customer3.Surname = "Jones";
customer3.AnnualSpend = 1500;
Customer[] customers = new Customer[] { customer1, customer2, customer3 };
Array.Sort(customers, new AnnualSpendComparer());
/* RESULTS
Jim Smith, £1000
Bob Jones, £1500
Bob Smith, £2000
*/
Try changing the comparer to a NameComparer to see the Customers ordered by surname and forename.
Array.Sort(customers, new NameComparer());
/* RESULTS
Bob Jones, £1500
Bob Smith, £2000
Jim Smith, £1000
*/
19 January 2012