Click here to Skip to main content
10,500,000 members (72,292 online)
Click here to Skip to main content
Add your own
alternative version

Stats

122K views
47 bookmarked
Posted

Sorting Lists using IComparable and IComparer Interface in .NET

, 4 Oct 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Sorting Lists using IComparable and IComparer interface in .NET

Introduction

This article explains how to sort Lists by using two interfaces IComparable<> and IComparer<> provided by the .NET Framework.

Background

It's easy to sort a list of strings or integers by just calling the List.Sort() method, but how can we sort two objects and based on what field?

Let's look at a small example and see how we can solve the problem using IComparable<> and IComparer interfaces.

Example

Let's create a simple Employee class with two fields, Name and Salary.

class Employee 
{
     public string Name { get; set; }
     public int Salary { get; set; }
}

Now create a List of Employees and call Sort() method of a List.

// Use Collection Initializers( C# 3.0 ) to initialize the List             
List<Employee> empList = new List<Employee>() 
	{ new Employee { Name = "a", Salary = 14000 },
           new Employee { Name = "b", Salary = 13000 } 
         };
empList.Sort(); 

Oops! we got an exception!

The Exception says we need to implement IComparable<> interface,
List.Sort() sorts any class that implements IComparable<> Interface which has one method called CompareTo().

Let's implement IComparable<> interface to our Employee class:

class Employee : IComparable<Employee>
{
     public string Name { get; set; }
     public int Salary { get; set; }
        
     #region IComparable<Employee> Members
       
     public int CompareTo( Employee other )
     {
         if ( this.Salary < other.Salary ) return 1;
         else if ( this.Salary > other.Salary ) return -1;
         else return 0;
     }
        
     #endregion
}

In the above code, we are sorting objects based on salary of employee in descending order, by implementing CompareTo() method of IComparable interface which takes Employee reference as a parameter.
Now, calling empList.Sort() gives no exception and empList is well sorted by salary.

But sometimes, we may need to sort a list of objects when class does not implement IComparable<> interface and also we may need various kinds of sorting on that class like:

  1. Sort Employees by Salary in Ascending Order
  2. Sort Employees by Salary in Descending Order
  3. Sort Employees by Name

To solve this problem, .NET provides a special interface called IComparer<> which has a method Compare(), takes two object parameters X, Y and returns an int.
Use of IComparer<> interface tells List how exactly you want to sort.

class Employee_SortBySalaryByAscendingOrder : IComparer<Employee>
{
    #region IComparer<Employee> Members
    
    public int Compare( Employee x, Employee y )
    {
        if ( x.Salary > y.Salary ) return 1;
        else if ( x.Salary < y.Salary ) return -1;
        else return 0;
    }
    
    #endregion
}

class Employee_SortBySalaryByDescendingOrder : IComparer<Employee>
{
    #region IComparer<Employee> Members
    
    public int Compare( Employee x, Employee y )
    {
        if ( x.Salary < y.Salary ) return 1;
        else if ( x.Salary > y.Salary ) return -1;
        else return 0;
    }
    
    #endregion
}

class Employee_SortByName : IComparer<Employee>
{
    #region IComparer<Employee> Members
    
    public int Compare( Employee x, Employee y )
    {
        return string.Compare( x.Name, y.Name );
    }
    
    #endregion
}

The above code introduces three classes by implementing Compare() method of IComparer interface.

Now, how do we use this? We just have to pass the reference of these classes as a object parameter to Sort() method as shown below:

// Use Collection Initializers( C# 3.0 ) to initialize the List 
List<Employee> empList = new List<Employee>() 
		{ new Employee { Name = "a", Salary = 14000 },
                    new Employee { Name = "b", Salary = 13000 } 
                  };
                                     
Employee_SortBySalaryByAscendingOrder eAsc = 
		new Employee_SortBySalaryByAscendingOrder(); 
// Sort Employees by salary by ascending order.   
empList.Sort( eAsc );
    
Employee_SortBySalaryByDescendingOrder eDsc = 
		new Employee_SortBySalaryByDescendingOrder();
// Sort Employees by salary by descending order. 
empList.Sort( eDsc );
    
Employee_SortByName eName = new Employee_SortByName();
// Sort Employees by their names.                                 
empList.Sort( eName );

Conclusion

Sorting Lists is simple as long as you sort basic elements like strings and integers for which comparison classes are defined.

Usage of IComparable<> and IComparer<> interface helps to sort Lists of objects on custom classes easily.

History

  • v1.0 - Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Abhishek D V
Technical Lead Wipro Technologies
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionIt doesn't work Pin
siglertl20-Dec-13 11:44
membersiglertl20-Dec-13 11:44 
GeneralMy vote of 4 Pin
khem thapa29-Jul-13 1:55
memberkhem thapa29-Jul-13 1:55 
GeneralMy vote of 4 Pin
trying826-May-13 11:51
membertrying826-May-13 11:51 
GeneralMy vote of 5 Pin
Shivprasad koirala11-Mar-13 8:52
mvpShivprasad koirala11-Mar-13 8:52 
GeneralNice article Pin
wknopf21-Feb-13 7:05
memberwknopf21-Feb-13 7:05 
GeneralMy vote of 5 Pin
dedlok10-Aug-12 11:06
memberdedlok10-Aug-12 11:06 
GeneralSimle and Effective Explanation Pin
Imtiaz.Ahmed30-Apr-11 3:00
memberImtiaz.Ahmed30-Apr-11 3:00 
GeneralGood article Pin
hammerstein059-Feb-10 3:58
memberhammerstein059-Feb-10 3:58 
GeneralNice Pin
Luc Pattyn5-Oct-09 7:56
mvpLuc Pattyn5-Oct-09 7:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 4 Oct 2009
Article Copyright 2009 by Abhishek D V
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid