IComparable Interface and Its Use in Sorting Types

Introduction

This article explains what the IComparable interface is, how to do sorting on simple types (such as int, string, float, and so on) and how to sort Complex Types using the IComparable interface.

IComparable Interface

This interface allows us to do sorting of value types or classes that implement sorting of its instance.

The IComparable interface comes in the following 2 flavors. 

  1. IComparable (Non Generic)
  2. IComparable<T> (Generic), where T is the type of object to compare.

IComparable

The IComparable interface provides 1method named “CompareTo(Object obj)”. This method takes an Object as parameter and compares the current instance with another object of the same type. Please find the following syntax for it.

Syntax: int CompareTo(object obj);

This method returns an integer value, please find the following table for its meaning and example.

IComparable<T>

The IComparable<T> interface is the generic version that provides 1 method named “CompareTo(T others)”, the generic version of this interface provides a more type-safe manner to handle the comparison between objects. Please find the following syntax for it.

Syntax: int CompareTo(T other);

Where "T" is the type of object and "other" is an object to compare with the current object.

This method takes type as parameter and compares the current object with another object of the same type.

Please find the following table for its meaning and example.

Value Meaning Example
-1 If current instance is less than other object int a = 2; a.CompareTo(3)
0 If current instance is equal to other object int a = 2; a.CompareTo(2)
1 If current instance greater than other object int a = 2; a.CompareTo(1)

Now, let's play with an example.

First we'll see a Simple Type and we'll do sorting on them and then later on we'll see how to sort Complex Types such as User Defined Types.

So, there are several Simple Types available in .NET, like int, string, double, float, char, decimal and so on.

We'll take int to do the sorting in our example.

Create a new project named “IComparableInterface” and create a list of integers as shown below:

  1. static void Main(string[] args)  
  2. {  
  3.     List<int> numbers = new List<int>() { 2, 6, 4, 1, 0, 5, 9, 7, 5 };  
  4.     Console.WriteLine("Number before Sorting: \n");  
  5.     foreach (int no in numbers)  
  6.     {  
  7.         Console.Write("{0} ",no);  
  8.     }  
  9.     numbers.Sort();  
  10.     Console.WriteLine("\n\nNumber after Sorting: \n");  
  11.     foreach (int no in numbers)  
  12.     {  
  13.         Console.Write("{0} ", no);  
  14.     }   
  15.     Console.ReadLine();  
  16. }  
When we run our program, we'll get the following sorted output: 

Sorted Numbers Output

You can also do the same thing with string, double, float, char, decimal and so on.

Now, let's do sorting on Complex Types. Add a new class to your project named “Student” with some properties like, Name, Roll_No, Marks as shown below.

Student.cs

  1. class Student  
  2. {  
  3.     public int Roll_No { getset; }  
  4.     public string Name { getset; }  
  5.     public int Marks { getset; }  
  6. }  
Now create some objects of the Student class in the list in Main().
  1. Student s1 = new Student() { Roll_No = 3, Name = "Sunny", Marks = 10 };  
  2. Student s2 = new Student() { Roll_No = 5, Name = "Abhishek", Marks = 45 };  
  3. Student s3 = new Student() { Roll_No = 2, Name = "Raj", Marks = 30 };  
  4. Student s4 = new Student() { Roll_No = 4, Name = "Sandy", Marks = 28 };  
  5. Student s5 = new Student() { Roll_No = 1, Name = "Mahesh", Marks = 35 };  
  6.   
  7. List<Student> studentList = new List<Student>();  
  8. studentList.Add(s1);  
  9. studentList.Add(s2);  
  10. studentList.Add(s3);  
  11. studentList.Add(s4);  
  12. studentList.Add(s5);  
  13.   
  14. studentList.Sort();  
Now when we try to run our program for the code above, we'll get a runtime error as shown below: 

Invalid Operation Exception

We got this error because .NET doesn't know how to sort these Complex Types. So, we need to inform .NET of how these Complex Types are to be sorted. .NET doesn't know by which property objects need to be sorted.

Therefore, Sort() functionality doesn't work for Complex Types. Sort() functionality perfectly works for Simple Types, because these types already implement an IComparable Interface as shown below:

Code View

And, that Interface contains the following method to do sorting:

Interface Review

So, this method is already implemented in Simple Type by .NET framework. And, because of this only, .NET knows how to sort integers, strings, and so on.

So, we're going to implement an IComparable<T> interface to do sorting on Complex Types.

Now update your Student class with the following implemented code.

Student.cs

  1. class Student : IComparable<Student>  
  2. {  
  3.     public int Roll_No { getset; }  
  4.     public string Name { getset; }  
  5.     public int Marks { getset; }  
  6. }  
  7.   
  8. public int CompareTo(Student other)  
  9. {  
  10.     return this.Roll_No.CompareTo(other.Roll_No);  
  11. }  
Now after this implementation, we informed the .NET environment to sort student objects by their Roll_No.

If you want to sort it by Name, use: return this.Name.CompareTo(other.Name);

If you want to sort it by Marks, use: return this.Marks.CompareTo(other.Marks);

Update your Main() as shown below:

Program.cs
  1. Student s1 = new Student() { Roll_No = 3, Name = "Sunny", Marks = 10 };  
  2. Student s2 = new Student() { Roll_No = 5, Name = "Abhishek", Marks = 45 };  
  3. Student s3 = new Student() { Roll_No = 2, Name = "Raj", Marks = 30 };  
  4. Student s4 = new Student() { Roll_No = 4, Name = "Sandy", Marks = 28 };  
  5. Student s5 = new Student() { Roll_No = 1, Name = "Mahesh", Marks = 35 };  
  6.   
  7. List<Student> studentList = new List<Student>();  
  8. studentList.Add(s1);  
  9. studentList.Add(s2);  
  10. studentList.Add(s3);  
  11. studentList.Add(s4);  
  12. studentList.Add(s5);  
  13.   
  14. Console.WriteLine("Students before Sorting: ");  
  15. foreach (Student st in studentList)  
  16. {  
  17.     Console.WriteLine("Roll No: {0}\tName: {1}\tMarks: {2}",st.Roll_No,st.Name,st.Marks);  
  18. }  
  19.   
  20. studentList.Sort();  
  21.   
  22. Console.WriteLine("\nStudents after Sorting: ");  
  23. foreach (Student st in studentList)  
  24. {  
  25.     Console.WriteLine("Roll No: {0}\tName: {1}\tMarks: {2}", st.Roll_No, st.Name, st.Marks);  
  26. }  
When you run your program, the Student objects will be sorted depending on Roll_No as in the following:

Sorting Operation Output

Conclusion

So, whenever you wish to sort any Complex Type or any User Defined Type, implement an IComparable interface in your class and write logic inside CompareTo().

I hope this article helps you to understand the IComparable interface and its use in Sorting.

If there's any mistake in this article please let me know. Please provide your valuable feedback and comments, that enable me to provide a better article the next time.

Up Next
    Ebook Download
    View all
    Learn
    View all