Sorting an Array of Custom Objects in C#
page 1 of 4
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): 3862/ 417

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.


View Entire Article

Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 4 and 7 and type the answer here:

User Comments

Title: Nice one   
Name: Ravi Sadalagi
Date: 8/12/2008 6:05:44 AM
Comment:
good one thank you..
Title: Excellent   
Name: Nancy
Date: 8/11/2008 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: 8/11/2008 4:46:47 AM
Comment:
good article
Title: good   
Name: Neetu Tiwari
Date: 8/9/2008 6:55:21 AM
Comment:
Its good.....thanks
Title: Mr   
Name: Priyan R
Date: 7/29/2008 2:18:41 AM
Comment:
Hi thanks good article

Product Spotlight
Product Spotlight 
Learn More
.NET Tools
asp.net shopping cart
asp.net chart control






Ads Powered by Lake Quincy Media
Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2008 ASPAlliance.com  |  Page Processed at 9/6/2008 11:12:13 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search