Step 1: Implement the IComparable interface
Listing 3
Step 2: Define the CompareTo method.
In this example we will be sorting by the Make property of
the Car Class.
Listing 4
public int CompareTo(object obj)
{
if (obj is Car)
{
Car c2 = (Car)obj;
return Make.CompareTo(c2.Make);
}
else
throw new ArgumentException("Object is not of type Car.");
}
That is it! We are now ready to test if our sorting works.
Step 3: Test Sorting by Make.
Listing 5
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 = "California";
carArray.Add(objCar);
objCar = null;
carArray.Sort();
You will now observe that the carArray is sorted
alphabetically by Make.
Note: Sometimes instead of using the ArrayList, it is
possible that you are working with an object array. You can use the C# built in
Adapter() method as shown below.
To convert from an array to ArrayList use:
ArrayList carArray = ArrayList.Adapter(carObjectArray);
To convert from an ArrayList to object array use:
Car[] carObjectArray = (Car[])carArray.ToArray(typeof(Car));