Suppose that you want to sort an array of integers, numbers then it can be easily done using Array.Sort(numbers); but if you want to sort an array of Employee, employees by age then you cannot write Array.Sort(employees). You will get System.InvalidOperationException: 'Failed to compare two elements in the array.' exception message.
To get rid of this exception message, you should implement the Employee class with IComparable.
IComparable is used to compare two or more objects of same class and sort the objects based on some property e.g. Age. IComparable defines object ordering. This interface has only one method: CompareTo(object? obj).
Definition of IComparable: IComparable compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
Example. The following Employee class implements IComparable.
Client side code inside Main method:
C# Simple Example of IComparable Part-2
class Employee : IComparable
{
private int _Age;
// initialize data using CTOR
public Employee(int id, string name, int age)
{
Id = id;
Name = name;
Age = age;
}
// to get data, we need properties
public int Id { get; } // read-only, Id cannot be updated
public string? Name { get; set; } // read-write, name can be updated
public int Age // read-write, age can be updated
{
get { return _Age; }
set
{
if (value < 18)
{
throw new ArgumentException("Age must be above 18");
}
else
{
_Age = value;
}
}
}
public int CompareTo(object? obj)
{
if (obj is Employee emp)
{
if (this.Age > emp.Age)
{
return 1;
}
else if(this.Age < emp.Age)
{
return -1;
}
else
{
return 0;
}
}
else
{
throw new Exception("Invalid Data");
}
}
}Employee[] employees = new Employee[5];
employees[0] = new Employee(1001,"Bhim",35);
employees[1] = new Employee(1002,"Ajay",25);
employees[2] = new Employee(1003,"Vijay",43);
employees[3] = new Employee(1004,"Rakesh",27);
employees[4] = new Employee(1005,"Mohan",22);
Console.WriteLine("original array ==>");
foreach (var emp in employees)
{
Console.WriteLine($"Id {emp.Id}, Name {emp.Name}, Age {emp.Age}");
}
// array of employees sorted by age
Array.Sort<Employee>(employees); // Syntax: Sort<T>(T[] array)
Console.WriteLine("\nsorted by Age ==>");
foreach (var emp in employees)
{
Console.WriteLine($"Age {emp.Age}, Id {emp.Id}, Name {emp.Name}");
}OUTPUT
original array ==>
Id 1001, Name Bhim, Age 35
Id 1002, Name Ajay, Age 25
Id 1003, Name Vijay, Age 43
Id 1004, Name Rakesh, Age 27
Id 1005, Name Mohan, Age 22
sorted by Age ==>
Age 22, Id 1005, Name Mohan
Age 25, Id 1002, Name Ajay
Age 27, Id 1004, Name Rakesh
Age 35, Id 1001, Name Bhim
Age 43, Id 1003, Name Vijay
C# Simple Example of IComparable Part-3
No comments:
Post a Comment