When you have an Array
or List<>
of types such as string or integer that already support
IComparer
,
you can sort that array or list without providing any explicit reference to
IComparer
. In that case, the elements of the array are cast to the default implementation
of IComparer
(Comparer.Default
) for you.
List<string> list = new List<string>();
list.Sort();
But when you have user defined objects, you must implement either or both of these interfaces:
IComparable
IComparer
IComparable
namespace sorting
{
class Program
{
public static List<student> students = new List<student>();
static void Main(string[] args)
{
students.Add(new student("Yeshani", 22));
students.Add(new student("Dhanushka", 25));
students.Add(new student("Madushan", 27));
students.Sort();
foreach (student n in students)
{
Console.WriteLine(n.name);
}
Console.ReadLine();
}
}
public class student:IComparable<student>
{
public string name;
public int age;
public student(string name, int age)
{
this.name = name;
this.age = age;
}
public int CompareTo(student b)
{
return this.name.CompareTo(b.name);
}
}
}
When a class implements the IComparable
interface, we must also implement the public method
CompareTo(T)
. In the CompareTo
method, we can write our sorting algorithm.
In here I have sorted the list on student name alphabetically.
We use IComparable<T>
when the class has an intrinsic comparison.
We need to know the sorting criteria before we start.
In here we have to decide whether to sort on age or name before we implement the class. But in some situations we may need various kinds of sorting on a class.
To solve this problem, .NET provides a special interface called IComparer<>
which has a method Compare()
,
that takes two object parameters X
,
Y
and returns an int
. The use of the IComparer<>
interface tells List
how exactly you want to sort.
IComparer
We use IComparer
when you want a comparison method other than the class intrinsic comparison, if it has one.
namespace sorting
{
class Program
{
public static List<student> students = new List<student>();
static void Main(string[] args)
{
students.Add(new student("Yeshani", 22));
students.Add(new student("Dhanushka", 25));
students.Add(new student("Madushan", 27));
sortOnAge soa = new sortOnAge();
students.Sort(soa);
foreach (student n in students)
{
Console.WriteLine(n.name);
}
Console.ReadLine();
}
}
public class student:IComparable<student>
{
public string name;
public int age;
public student(string name, int age)
{
this.name = name;
this.age = age;
}
public int CompareTo(student b)
{
return this.name.CompareTo(b.name);
}
}
public class sortOnAge : IComparer<student>
{
public int Compare(student a, student b)
{
if (a.age > b.age) return 1;
else if (a.age < b.age) return -1;
else return 0;
}
}
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.