Using The IComparable And IComparer Interface In C#

Introduction

 
One of the most used functionalities in our C# classes is the ability to sort the different instances of a class. This is mostly done when we create a generic List of our class type and next, we want to sort our class based on some condition. Today, we will see how this is done in our C# classes
 

Creating the Class

 
We will create a .NET core console application using Visual Studio 2019 Community edition as below,
 
Using The IComparable And IComparer Interface In C#
 
Using The IComparable And IComparer Interface In C#
Next, we create a Student Class inside the “Program.cs” file as below,
  1. public class Student : IComparable<Student>  
  2. {  
  3.   
  4.     public int ID { getset; }  
  5.     public string Name { getset; }  
  6.     public string Program { getset; }  
  7.     public int Year { getset; }  
  8.     public float GPA { getset; }  
  9.   
  10.     public int CompareTo(Student otherItem)  
  11.     {  
  12.         var status = (this.GPA > otherItem.GPA) ? 1 : ((this.GPA == otherItem.GPA) ? 0 : -1);   
  13.         return status;  
  14.     }  
  15. }  
Let us look at the code in detail. To make the class sortable we need to implement the IComparable<T> interface. In this interface we need to code the “CompareTo” function. In this function another instance of the same class is passed in and then we compare the two to order them. We base this on the GPA field and hence when we sort a List<Student> list, we will get the class items sorted by GPA in ascending order. Note that if the return value is zero, this means that the classes are equal in sort order, if the return value is 1 (positive number), then the current class is higher in the sort and if the value is -1 (negative number) then the input class is higher in the sort order.
 
To test this out, we write the following code in the Main function as below,
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.   
  6.             var students = new List<Student>();  
  7.   
  8.             var studentA = new Student() { ID = 1, Name = "John Doe", Program = "BCS", Year = 2020, GPA = 2.75F };  
  9.             var studentB = new Student() { ID = 1, Name = "Jane Doe", Program = "BCS", Year = 2020, GPA = 3.4F };  
  10.             var studentC = new Student() { ID = 1, Name = "Mary Jane", Program = "BCS", Year = 2020, GPA = 2.71F };  
  11.   
  12.             students.Add(studentA);  
  13.             students.Add(studentB);  
  14.             students.Add(studentC);  
  15.   
  16.             Console.WriteLine($"Items not in any order");  
  17.             foreach(var student in students)  
  18.             {  
  19.                 Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}");  
  20.             }  
  21.   
  22.             Console.WriteLine();  
  23.   
  24.             students.Sort();  
  25.   
  26.             Console.WriteLine($"Items in ascending order");  
  27.             foreach (var student in students)  
  28.             {  
  29.                 Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}");  
  30.             }  
  31.   
  32.             Console.WriteLine();  
  33.   
  34.             students.Sort(new DescendingComparer());  
  35.   
  36.             Console.WriteLine($"Items in descending order");  
  37.             foreach (var student in students)  
  38.             {  
  39.                 Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}");  
  40.             }  
  41.   
  42.             Console.ReadKey();  
  43.         }  
  44.     }  
  45.   
  46.     public class DescendingComparer : IComparer<Student>  
  47.     {  
  48.         public int Compare(Student a, Student b)  
  49.         {  
  50.             var status = (a.GPA > b.GPA) ? -1 : ((a.GPA == b.GPA) ? 0 : 1);  
  51.             return status;  
  52.         }  
  53.     }  
In the first case, we print the list of student classes as entered in the list. Then, we sort the list which will list the students in ascending order based on the GPA field. Finally, if we want to reverse the order and sort the student classes in descending order by GPA field we create a new DescendingComparer class which implements the IComparer<Student> interface and sort the records in the reverse order of what we did before.
 
Below is the result,
 
Using The IComparable And IComparer Interface In C#
 

Summary

 
In this article, we have looked at how we can implement the IComparable<T> class and make a class sortable based on the condition we like. This is the default sorter. We also saw how we can pass a custom class implementing IComparer<T> and sort the list of classes on demand.


Similar Articles