Introduction
This Tip/Trick is an alternative to the original tip Sorting using C# Lists[^].
You often face the issue that a given class has not one Collating Sequence[^] but many various ways to order the class objects. This alternative tip shows how to choose the ordering without depending on the class implementing IComparable[^].
Sorting alternatives to "hard coded" IComparable dependency
A class that has no natural
Collating Sequence[
^] should not implement
IComparable<T>
. Instead, one should use a per case defined ordering. Some concise solutions are shown below. They do not need any definition of any additional
IComparer
class nor do they require the element class to implement
IComparable
.
By LINQ means
Sorting by LINQ is as follows:
var querySortedByProperty = from element in collection
orderby element.property
select element;
foreach(var item in querySortedByProperty) { ... }
By Enumerable extension methods
Sorting equivalent to LINQ by
Enumerable[
^] extension method calls:
var querySortedByProperty = collection.OrderBy(e=>e.property);
foreach(var item in querySortedByProperty) { ... }
By Sorting overload
Sorting a colleciton is also possible by a
Sort
overload that takes a delegate for ordering the elements of the collection:
collection.Sort((a,b)=>a.property.CompareTo(b.property));
foreach(var item in colleciton) { ... }
Using the code
Assuming the following class analogous to the one from the original tip without implementing IComparable<T>
.
public class Student
{
public string Name { get; private set; }
public int Age { get; private set; }
public Student(string name, int age)
{
Name = name;
Age = age;
}
}
Linq:
var querySortByName = from s in students orderby s.Name select s;
var querySortByAge = from s in students orderby s.Age select s;
Extension methods:
var querySortByName = students.Orderby(s=>s.Name);
var querySortByAge = students.Orderby(s=>s.Age);
Sort collection:
students.Sort((a,b)=>a.Name.CompareTo(b.Name));
students.Sort((a,b)=>a.Age.CompareTo(b.Age));
Points of Interest
Checkout 101 LINQ samples[^]. That gives many first steps on LINQ operations.
History
V1.0 | 2013-01-26 | Initial version. |
V1.1 | 2013-01-28 | Fixed some typos. |