Sorting items in a collection is a common requirement specially when the collection contains lots of items.If our collection contains primitive type only then we can easily sort the items in the collection by just calling the sort method.
So if declare a collection of integers as
List<int> lst = new List<int>{34,3,544,5,743,14,5425};
Then we just need to call the Sort() method on the collection and the items will be sorted.
lst.Sort();
If we iterate through the items we can see that they are sorted in ascending order
foreach (int item in lst) { Console.WriteLine(item); }
Though we can use the Sort() method to sort collections of primitive types but we can not just sort a collection of custom types using the Sort() method.If we try to call the Sort() method on a collection of custom type then we will get an error.
So if we have defined a Student class as:
class Student { public string Name { get; set; } public int TotalMarks { get; set; } public int Standard { get; set; } public Student() { } public int CompareTo(Student student) { return student.TotalMarks.CompareTo(this.TotalMarks); } }
then if we call the Sort() method on a collection of Student type then we will get an exception
List<Student> lst = new List<Student>{ new Student { Name = "Amit", Standard = 8, TotalMarks = 80 }, new Student { Name = "Mike", Standard = 8, TotalMarks = 60 }, new Student { Name = "Jenny", Standard = 8, TotalMarks = 100 }, new Student { Name = "Ajay", Standard = 8, TotalMarks = 70 } }; lst.Sort();
To sort collections of custom types our collection needs to implement the IComparable<T> interface.This interface is implemented by the primitive types that’s why we are able to call the Sort() method on a collection of primitive types.
To sort a collection of Student type we can implement the IComparable<Student>
interface.
class Student:IComparable<Student> { public string Name { get; set; } public int TotalMarks { get; set; } public int Standard { get; set; } public Student() { } public int CompareTo(Student student) { return student.TotalMarks.CompareTo(this.TotalMarks); } }
We can now sort the Student collection using the Sort method as
List<Student> lst = new List<Student>{ new Student { Name = "Amit", Standard = 8, TotalMarks = 80 }, new Student { Name = "Mike", Standard = 8, TotalMarks = 60 }, new Student { Name = "Jenny", Standard = 8, TotalMarks = 100 }, new Student { Name = "Ajay", Standard = 8, TotalMarks = 70 } }; lst.Sort(); foreach (Student stud in lst) { Console.WriteLine("Name={0} ,Marks={1}", stud.Name, stud.TotalMarks); }
Leave a Reply