Sorting an Array of Custom Objects in C#
 
Published: 23 Jul 2008
Abstract
In this article Sandesh discusses the different ways of sorting an array of custom objects in C# using the IComparable and IComparer interfaces. Examples are provided on the simple case of sorting an array of built in data types and extends the example to custom objects. He demonstrates the concepts with the help of code samples along with relevant analysis for each one of them.
by Sandesh Meda
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 40741/ 68

Description

Consider a simple case of sorting an array of strings in C#. We can simply call the Sort() method to sort the array.

Listing 1

ArrayList carArray = new ArrayList();
carArray.Add("Corvette");
carArray.Add("Honda");
carArray.Add("BMW");
carArray.Sort();

If you observe the contents of the array after the Sort(), you will notice that the elements are sorted alphabetically ie., "BMW," "Corvette," "Honda."

However, consider a Car Class as shown in Listing 2.

Listing 2

class Car 
{
  public string Make { set; get; }
  public int Year { set; get; }
  public string Location { set; get; }
}

If you create an ArrayList of car objects and try to Sort() it, it would throw an exception. You will need to have the Car class implement the IComparable interface and define the CompareTo method to be able to sort custom objects.

Method 1: Implementing the IComparable Interface

Step 1: Implement the IComparable interface

Listing 3

class Car : IComparable

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));
Method 2: Using the IComparer Interface

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
Conclusion

This article demonstrates different ways of sorting an array of custom objects. It provides a step-by-step approach in using the IComparable interface and in creating a Comparer class for sorting. Happy Sorting!!!



User Comments

Title: Great   
Name: peter
Date: 2011-09-02 5:41:56 AM
Comment:
Great great article
Title: Thanx   
Name: Stef
Date: 2010-02-03 4:10:36 PM
Comment:
This was a clear explanation..It helped me allot!
Title: nice post   
Name: simi
Date: 2009-12-30 2:13:53 AM
Comment:
hi,

First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

There is a good C# resource site, Have alook

http://www.csharptalk.com/2009/09/c-array.html
http://www.csharptalk.com/2009/10/creating-arrays.html

simi
Title: Mast hai   
Name: Niraj kumar
Date: 2009-06-05 8:58:00 AM
Comment:
Best explanation
Title: Well Done   
Name: jj
Date: 2009-06-03 2:28:54 AM
Comment:
This is good work
Title: Excelent   
Name: Awais Ranjha
Date: 2009-05-11 4:52:25 PM
Comment:
This is a great help. i am really thankful to the author. Really excellent article. Thanks a lot!
Title: Coustom object   
Name: shatendra singh
Date: 2009-05-02 6:34:28 AM
Comment:
this is very well artical.
Title: Great   
Name: Anton
Date: 2009-01-14 2:13:57 PM
Comment:
Thnx, very helpful
Title: great explanation   
Name: Aga
Date: 2008-11-28 11:50:20 PM
Comment:
Thanks so much for giving great explanation of the subject!
Title: Useful one   
Name: Chennai Tours Travels
Date: 2008-10-20 3:56:09 AM
Comment:
Nice explanation Sandesh Meda
Good effort ..
Title: Nice one   
Name: Ravi Sadalagi
Date: 2008-08-12 6:05:44 AM
Comment:
good one thank you..
Title: Excellent   
Name: Nancy
Date: 2008-08-11 10:23:58 AM
Comment:
Makes a great attempt to explain sorting an array of custom objects in a very easy understandable way. Really excellent article. Thanks a lot!
Title: Mr   
Name: Amook Vandan
Date: 2008-08-11 4:46:47 AM
Comment:
good article
Title: good   
Name: Neetu Tiwari
Date: 2008-08-09 6:55:21 AM
Comment:
Its good.....thanks
Title: Mr   
Name: Priyan R
Date: 2008-07-29 2:18:41 AM
Comment:
Hi thanks good article






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-11-26 11:15:07 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search