Sort Array List Of Objects In C# (IComparable And IComparator)

Today I am going to explain how to sort the ArrayList of objects using two properties; IComparable and IComparator Interface.
 
Before  implementing it using  Comparable and Comparator Interface, let's see what happens if we use "Collections.Sort()" like we use for normal ArrayList
 
Let us create an Employee class which has "empId","empName","empAge" as properties in it. Now I want ArrayList of Employee object type.
 
Code for Employee Class,
  1. public class Employee  
  2.    {  
  3.        private int empId;  
  4.        private string empName;  
  5.        private int empAge;  
  6.   
  7.        public Employee(int empId, string empName, int empAge)  
  8.        {  
  9.            this.empId = empId;  
  10.            this.empName = empName;  
  11.            this.empAge = empAge;  
  12.        }  
  13.   
  14.        public string GetEmployeeName()  
  15.        {  
  16.            return empName;  
  17.        }  
  18.   
  19.        public void SetEmployeeName(string empName)  
  20.        {  
  21.            this.empName = empName;  
  22.        }  
  23.   
  24.        public int GetEmployeeID()  
  25.        {  
  26.            return empId;  
  27.        }  
  28.   
  29.        public void SetEmployeeID(int empId)  
  30.        {  
  31.            this.empId = empId;  
  32.        }  
  33.   
  34.        public int GetEmployeeAge()  
  35.        {  
  36.            return empAge;  
  37.        }  
  38.        public void SetEmployeeAge(int empAge)  
  39.        {  
  40.            this.empAge = empAge;  
  41.        }  
  42.   
  43.    }  
Now let us look in to the main method, and we shall sort it using "Collections.Sort()"
  1. public static void Main(string[] args)  
  2.        {  
  3.            var employeeList = new ArrayList();  
  4.            employeeList.Add(new Employee(10, "Test1", 26));  
  5.            employeeList.Add(new Employee(20, "Test2", 36));  
  6.            employeeList.Add(new Employee(30, "Test3", 46));  
  7.   
  8.            employeeList.Sort();  
  9.            foreach(var emp in employeeList)  
  10.            {  
  11.                Console.WriteLine(emp);  
  12.            }  
  13.   
  14.        }  
Now let us see what output it gives.
 
Sort Array List Of Objects In C# (IComparable And IComparator)
 
We encountered an Exception. Look at the exception -- it says:  "System.Invalid.Operation". That means Sort() method is only used to sort normal array list with "integers" or "string" types. But for sorting the complex types, it will not know which type to sort (Ex: EmpAge or EmpSalary). So we get an error, "invalid operation".
 
Let us see what  IComparable Interface is. 
  • We use IComparable Interface to sort elements. It is used to compare the current instance with another object of the same type. It is of type integer.
  • It gives us "compareTo()" to implement, while comparing two objects  of similar type.
Syntax
 
public class ClassName : IComparable<ClassName>
 
You need to implement method inside the  "IComparable" interface. Please find the below code snippet
  1. public class Employee : IComparable<Employee>  
  2.    {  
  3.        private int empId;  
  4.        private string empName;  
  5.        private int empAge;  
  6.   
  7.        public Employee(int empId, string empName, int empAge)  
  8.        {  
  9.            this.empId = empId;  
  10.            this.empName = empName;  
  11.            this.empAge = empAge;  
  12.        }  
  13.   
  14.        public string GetEmployeeName()  
  15.        {  
  16.            return empName;  
  17.        }  
  18.   
  19.        public void SetEmployeeName(string empName)  
  20.        {  
  21.            this.empName = empName;  
  22.        }  
  23.   
  24.        public int GetEmployeeID()  
  25.        {  
  26.            return empId;  
  27.        }  
  28.   
  29.        public void SetEmployeeID(int empId)  
  30.        {  
  31.            this.empId = empId;  
  32.        }  
  33.   
  34.        public int GetEmployeeAge()  
  35.        {  
  36.            return empAge;  
  37.        }  
  38.        public void SetEmployeeAge(int empAge)  
  39.        {  
  40.            this.empAge = empAge;  
  41.        }  
  42.   
  43.        public int CompareTo(Employee obj)  
  44.        {  
  45.            return empAge.CompareTo(obj.empAge);  
  46.   
  47.        }  
  48.          
  49.    }  
In the above class we have implemented the method "compareTo()" based on EmpAge. Now let us look at the Main method and o/p
  1. //using IComperable, Sorting by age  
  2.            List<Employee> listOfemployees = new List<Employee>();  
  3.            listOfemployees.Add(new Employee(100, "John", 30));  
  4.            listOfemployees.Add(new Employee(600, "Kate", 42));  
  5.            listOfemployees.Add(new Employee(30, "William", 41));  
  6.            listOfemployees.Add(new Employee(50, "George", 10));  
  7.            listOfemployees.Add(new Employee(500, "Charlotte", 50));  
  8.   
  9.            listOfemployees.Sort();  
  10.            foreach(var emp in listOfemployees)  
  11.            {  
  12.                Console.WriteLine(emp.GetEmployeeAge());  
  13.            }  
Sort Array List Of Objects In C# (IComparable And IComparator) 
 
ICompareble Interface can sort the elements only one at a time, i.e it can only sort one field at a time.  Like I have mentioned in the above example, I have sorted using age field
 
Let us see IComparer Interface.
  • Used to sort the element that compares two objects
  • It has Compare() method to implement
Now let us look at the example and see how we can implement Employee class using IComparer Interface:
  1.  public class Employee  
  2.     {  
  3.         private int empId;  
  4.         private string empName;  
  5.         private int empAge;  
  6.   
  7.         public Employee(int empId, string empName, int empAge)  
  8.         {  
  9.             this.empId = empId;  
  10.             this.empName = empName;  
  11.             this.empAge = empAge;  
  12.         }  
  13.   
  14.         public string GetEmployeeName()  
  15.         {  
  16.             return empName;  
  17.         }  
  18.   
  19.         public void SetEmployeeName(string empName)  
  20.         {  
  21.             this.empName = empName;  
  22.         }  
  23.   
  24.         public int GetEmployeeID()  
  25.         {  
  26.             return empId;  
  27.         }  
  28.   
  29.         public void SetEmployeeID(int empId)  
  30.         {  
  31.             this.empId = empId;  
  32.         }  
  33.   
  34.         public int GetEmployeeAge()  
  35.         {  
  36.             return empAge;  
  37.         }  
  38.         public void SetEmployeeAge(int empAge)  
  39.         {  
  40.             this.empAge = empAge;  
  41.         }  
  42.     }  
  43.     public class EmployeeComparer : IComparer<Employee>  
  44.     {  
  45.           
  46.         public enum sortBy  
  47.         {  
  48.             empId,  
  49.             empName,  
  50.             empAge  
  51.         }  
  52.   
  53.         //Sort two employee Ages  
  54.         public sortBy compareByFields = sortBy.empAge;  
  55.         public int Compare(Employee x, Employee y)  
  56.         {  
  57.             switch (compareByFields)  
  58.             {  
  59.                 case sortBy.empAge:  
  60.                     return x.GetEmployeeAge().CompareTo(y.GetEmployeeAge());  
  61.                 case sortBy.empName:  
  62.                     return x.GetEmployeeName().CompareTo(y.GetEmployeeName());  
  63.                 case sortBy.empId:  
  64.                     return x.GetEmployeeID().CompareTo(y.GetEmployeeID());  
  65.                 default:break;  
  66.   
  67.             }  
  68.             return x.GetEmployeeAge().CompareTo(y.GetEmployeeAge());  
  69.   
  70.         }  
  71. }  
 Let us see the main method and output:
  1. List<Employee> listOfemployees = new List<Employee>();  
  2.             listOfemployees.Add(new Employee(100, "John", 30));  
  3.             listOfemployees.Add(new Employee(600, "Kate", 42));  
  4.             listOfemployees.Add(new Employee(30, "William", 41));  
  5.             listOfemployees.Add(new Employee(50, "George", 10));  
  6.             listOfemployees.Add(new Employee(500, "Charlotte", 50));  
  7.   
  8.             //sort the person with employee Name  
  9.             EmployeeComparer compare = new EmployeeComparer();  
  10.             compare.compareByFields = EmployeeComparer.sortBy.empName;  
  11.   
  12.             listOfemployees.Sort(compare);  
  13.             foreach (var emp in listOfemployees)  
  14.             {  
  15.                 Console.WriteLine(emp.GetEmployeeName());  
  16.             }  
  17.             Console.WriteLine("************Sort By Age**************");  
  18.             //sort the person with employee age  
  19.             compare.compareByFields = EmployeeComparer.sortBy.empAge;  
  20.   
  21.             listOfemployees.Sort(compare);  
  22.             foreach (var emp in listOfemployees)  
  23.             {  
  24.                 Console.WriteLine(emp.GetEmployeeName() + " " + emp.GetEmployeeAge());  
  25.             }  
  26.             Console.WriteLine("************Sort By EmployeeID**************");  
  27.             compare.compareByFields = EmployeeComparer.sortBy.empId;  
  28.   
  29.             listOfemployees.Sort(compare);  
  30.             foreach (var emp in listOfemployees)  
  31.             {  
  32.                 Console.WriteLine(emp.GetEmployeeName() + " " + emp.GetEmployeeID());  
  33.             }  
  34.           
Sort Array List Of Objects In C# (IComparable And IComparator)
 
In the abov, you can see that we have sorted elements by all fields in the "Employee" class. 
 
Source code is attached below. 
 
This is how you can sort the array of objects. That's it for this article. I hope you guys enjoyed this article. 
 
If there are any changes or anything needs to be added, please feel free to comment below. 
 
Thank you !!!


Similar Articles