In case you want to compare 2 objects for sorting purpose you can use this interface. IComparable defines a type specific comparison method. Value types and classes can implement this interface.
Lets say you have a list of people and you want to sort it by age. You'll use Sort method comes with the list. Usually the Sort() method will use default comparer for the type specified by the generic argument, Here default comparer for Person.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Person p1 = new Person() { Name = "Person 1", Age = 34 }; | |
Person p2 = new Person() { Name = "Person 2", Age = 31 }; | |
Person p3 = new Person() { Name = "Person 3", Age = 33 }; | |
Person p4 = new Person() { Name = "Person 4", Age = 26 }; | |
List<Person> people = new List<Person> { p1, p2, p3, p4 }; | |
//Exception : Failed to compare two elements in the array | |
people.Sort(); | |
} | |
} | |
public class Person | |
{ | |
public string Name { get; set; } | |
public int Age { get; set; } | |
} |
But it'll throw an error when trying to sort because Person does not have a comparer and it does not know how to sort them. Therefore you need to implement IComparable and its CompareTo method like below.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Person : IComparable | |
{ | |
public string Name { get; set; } | |
public int Age { get; set; } | |
public int CompareTo(Object obj) | |
{ | |
Person otherPerson = obj as Person; | |
if (otherPerson == null) | |
{ | |
throw new ArgumentNullException(); | |
} | |
else | |
{ | |
return Age.CompareTo(otherPerson.Age); | |
} | |
} | |
} |
Now the sorting will happen successfully. Note that implementation of CompareTo(Object) must return a Int32. All numeric types such as Int32 and Double implements IComparable.
Resources
0 comments:
Post a Comment