Sometimes, it might be necessary to have more flexibility in
your sorting, for example, to provide which property you want to sort the Car
array by. In situations like this, we would need to use the IComparer interface
and use the overloaded Sort method that takes the comparer instance as an
argument.
Step 1: Create a CarComparer class that implements the
IComparer interface
Listing 6
class CarComparer: IComparer
{
public enum ComparisonType
{
Make = 1, Year, Location
}
public ComparisonType ComparisonMethod
{
set;
get;
}
public int Compare(object x, object y)
{
Car c1;
Car c2;
if (x is Car)
c1 = x as Car;
else
throw new ArgumentException("Object is not of type Car.");
if (y is Car)
c2 = y as Car;
else
throw new ArgumentException("Object is not of type Car.");
return c1.CompareTo(c2, ComparisonMethod);
}
}
The main purpose of the CarComparer is to keep track of by what
property we are sorting. It has a ComparisonType enum that has the property
elements and an overloaded Compare method.
Step 2
Add an overloaded CompareTo to the Car class as shown in
Listing 7.
Listing 7
public int CompareTo(Car c2, CarComparer.ComparisonType comparisonType)
{
switch (comparisonType)
{
case CarComparer.ComparisonType.Make:
return Make.CompareTo(c2.Make);
case CarComparer.ComparisonType.Year:
return Year.CompareTo(c2.Year);
case CarComparer.ComparisonType.Location:
return Location.CompareTo(c2.Location);
default:
return Make.CompareTo(c2.Make);
}
}
That is it, we are done. We now have added the ability to
sort by Make, Year or Location. Let us test it out.
Step 3
Listing 8
Car objCar = new Car();
ArrayList carArray = new ArrayList();
objCar.Make = "BMW";
objCar.Year = 2008;
objCar.Location = "Florida";
carArray.Add(objCar);
objCar = null;
objCar = new Car();
objCar.Make = "Honda";
objCar.Year = 1996;
objCar.Location = "Illinois";
carArray.Add(objCar);
objCar = null;
objCar = new Car();
objCar.Make = "Corvette";
objCar.Year = 2006;
objCar.Location = "ZZ";
carArray.Add(objCar);
objCar = null;
CarComparer carComparer = new CarComparer();
carComparer.ComparisonMethod = CarComparer.ComparisonType.Location;
carArray.Sort(carComparer);
We use the overloaded Sort method that takes an instance of
the CarComparer class. To sort by other properties, change the ComparisonMethod
as shown below.
carComparer.ComparisonMethod = CarComparer.ComparisonType.Year