C Sharp Sort Lists
From Leo's Notes
This page was last edited on 5 December 2012, at 05:27.
The correct title of this article is C# Sort Lists.
Suppose that we have an object Item which contains a few properties such as:
- Age
- Name
List<Item> items = new List<Item>(); items.Add(...);
To sort items by age, do:
// This will sort it in ascending order.
items.Sort(delegate(Item a, Item b) {
return a.Age.CompareTo(b.Age);
});
Note that the a.CompareTo(b) method will return a positive value if a > b. When b > a, a.CompareTo(b) will return a negative value.