In this article, we are going to learn about the Comparer Class in C#.<p>
<h3>Need for Comparer Class</h3>
<p>For primitive data types, it is easy to compare two objects or variables.
For example, two integers can be easily compared using their numerical value. Two Strings can be compared
according to their lexicographical order.
But what about objects of classes which consists of different data types? How would the compiler know if one object
is equal to another object? What if we need to sort a list of objects? How would we define the comparison parameter for
two objects?
This is where the Comparer class comes in handy.
Comparer is an object-to-object comparer that allows us to compare objects recursively member by member
and to define custom comparison rules for certain properties, fields, or types.
Objects Comparer can be considered as a ready-to-use framework or as a starting point for similar solutions.
Let us consider a simple class as follows:
<pre>class Point {
public int x;
public int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
</pre>
This is a simple class which stores the co-ordinates of a point on the cartesian plane.
If we have a list of Point, List < Point > list_name = new List < Point >();
And we need to sort it according to the x - coordinate (ascending), and if two points
have the same x - coordinate, we compare the y - coordinate.
If we simply use list_name.Sort();
, it would throw an error.
So, we need to define a compare for the objects of the class Point.
<pre>
public class ComparePoint : Comparer < Point > {
public override int Compare(Point A, Point B) {
if (A.x != B.x) {
return A.x - B.x;
} else {
return A.y - B.y;
}
}
}
</pre>
We created a class ComparePoint which implements Comparer. Here, we override the Compare() function, which
checks for the equality of two objects and define our own conditions. Now, if we need to sort the list of Point:
list_name.Sort(new ComparePoint());
We just need to pass an instance of the ComparePoint class as a parameter to the Sort() function. Now, our list is sorted according to the conditions defined above.
A class Cube
is defined for you. Define two comparers in the code editor.
CompareDimension
: It sorts ascending for the length first. If the lengths are equal,
sort descending for breadth. If both are equal, sort ascending for height.CompareVolume
: It sorts ascending according to the volume of the cube.