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.
- IComparable (Non Generic)
- 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:
- static void Main(string[] args)
- {
- List<int> numbers = new List<int>() { 2, 6, 4, 1, 0, 5, 9, 7, 5 };
- Console.WriteLine("Number before Sorting: \n");
- foreach (int no in numbers)
- {
- Console.Write("{0} ",no);
- }
- numbers.Sort();
- Console.WriteLine("\n\nNumber after Sorting: \n");
- foreach (int no in numbers)
- {
- Console.Write("{0} ", no);
- }
- Console.ReadLine();
- }
When we run our program, we'll get the following sorted 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
- class Student
- {
- public int Roll_No { get; set; }
- public string Name { get; set; }
- public int Marks { get; set; }
- }
Now create some objects of the Student class in the list in Main().
- Student s1 = new Student() { Roll_No = 3, Name = "Sunny", Marks = 10 };
- Student s2 = new Student() { Roll_No = 5, Name = "Abhishek", Marks = 45 };
- Student s3 = new Student() { Roll_No = 2, Name = "Raj", Marks = 30 };
- Student s4 = new Student() { Roll_No = 4, Name = "Sandy", Marks = 28 };
- Student s5 = new Student() { Roll_No = 1, Name = "Mahesh", Marks = 35 };
-
- List<Student> studentList = new List<Student>();
- studentList.Add(s1);
- studentList.Add(s2);
- studentList.Add(s3);
- studentList.Add(s4);
- studentList.Add(s5);
-
- studentList.Sort();
Now when we try to run our program for the code above, we'll get a runtime error as shown below:
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:
And, that Interface contains the following method to do sorting:
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
- class Student : IComparable<Student>
- {
- public int Roll_No { get; set; }
- public string Name { get; set; }
- public int Marks { get; set; }
- }
-
- public int CompareTo(Student other)
- {
- return this.Roll_No.CompareTo(other.Roll_No);
- }
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
- Student s1 = new Student() { Roll_No = 3, Name = "Sunny", Marks = 10 };
- Student s2 = new Student() { Roll_No = 5, Name = "Abhishek", Marks = 45 };
- Student s3 = new Student() { Roll_No = 2, Name = "Raj", Marks = 30 };
- Student s4 = new Student() { Roll_No = 4, Name = "Sandy", Marks = 28 };
- Student s5 = new Student() { Roll_No = 1, Name = "Mahesh", Marks = 35 };
-
- List<Student> studentList = new List<Student>();
- studentList.Add(s1);
- studentList.Add(s2);
- studentList.Add(s3);
- studentList.Add(s4);
- studentList.Add(s5);
-
- Console.WriteLine("Students before Sorting: ");
- foreach (Student st in studentList)
- {
- Console.WriteLine("Roll No: {0}\tName: {1}\tMarks: {2}",st.Roll_No,st.Name,st.Marks);
- }
-
- studentList.Sort();
-
- Console.WriteLine("\nStudents after Sorting: ");
- foreach (Student st in studentList)
- {
- Console.WriteLine("Roll No: {0}\tName: {1}\tMarks: {2}", st.Roll_No, st.Name, st.Marks);
- }
When you run your program, the Student objects will be sorted depending on Roll_No as in the following:
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.