Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » C# Language » IComparable: Under the Hood

IComparable: Under the Hood

We now calling Array.Sort() on C# Types such as int, char, string will automatically do sorting based on that type.

Page Views : 16817
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Description:

We now calling Array.Sort() on C# Types such as int, char, string will automatically do sorting based on that type. But how do we sort array of Employee objects.To make this happen in C# follow the steps below: 

Step#1:

To sort an array of UDC(User Defined Class) objects. First inherit the interface IComparable and implement the method CompareTo.

Step#2:

In the Compare compare the fields the required for sorting and return -1,1,0 based the values if current object field value is greater than passed object field value then return 1 if both are equal then return 0 else return -1 

Step#3:

After done with two steps the Array.Sort() of our UDC objects is will work without any problem. 

Let's run through a coding sample which will make things clear: The source code has a classe called Employee which implements the Interface IComparable since this class is inheriting IComparable interface We have to code for CompareTo() Method which is done.

Source Code Explanation:

1. In the entry point of the Program i.e Main() the program starts with declaring array of employee objects of length 5.

2. Next each object is created using new operator and passing some values To constructor.

3. Next the call the Array.Sort(employees) this is were the IComparable Interface comes to use.When the call is encountered by C# it first looks whether the class implements IComparable interface if it so it looks for CompareTo() method if it is not there then it will cry.Since we have written this method what it will do it will perform quicksort for the array employee by comparing the field specified by us in CompareTo() method and perform necessary swapping of objects not swapping of values to sort the array. ie  when the second object is lesser than first object it swaps first object with second object rather than values of first object against second object.Because of this the Big O of sorting is always O(nlogn)  

4. Hot Tip: What we have if we want to sort the array in descending order rather than ascending simply reverse the return value of 1,-1 in the CompareTo() function.ie if the value of current object is greater then return -1 if it is lesser return 1

5. Now a question arises how to sort the array based on the User-Defined field the solution will be in the Next Article. 

Full Source Code:

// Source Code starts
using System;
class Employee:IComparable
{
private int Id;
private string Name;
public Employee(int id,string name)
{
this.Id=id;
this.Name=name;
}
public int CompareTo(object obj)
{
Employee temp=(Employee)obj;
if(this.Id>temp.Id)
{
return 1;
}
else
{
if(temp.Id==this.Id)
return 0;
else
return -1;
}
}
public static void Main()
{
Employee[] employees=
new Employee[5];
Console.WriteLine("Before Sort:");
for(int i=0;i<employees.Length;i++)
{
employees[i]=
new Employee(5-i,"Employee#" + i);
Console.Write(employees[i].Id + ",");
}
Console.WriteLine();
Array.Sort(employees);
Console.WriteLine("After Sort:");
for(int i=0;i<employees.Length;i++)
{
Console.Write(employees[i].Id + ",");
}
Console.WriteLine();
}
}
// Source Code End

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Prasad H
Prasad is working as a Software Development /Test Engineer in eBots Software (p) Ltd for ebots Inc .
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Generic IComparable? by David On July 15, 2010
Hi Prasad,

Thanks for the tutorial - can the Icomparable interface being parameterised so that the CompareTo method would not require a cast on the Object parameter? (in the case when we know we are solely dealing with a collection of one type)

Cheers,

David
Reply | Email | Modify 
Cool by Marcelo On February 16, 2011
Nice article. By the way, and answering David, you can use IComparable<T>, where the T is the entity by itself.
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.