C Sharp Sort Lists

From Leo's Notes
Revision as of 05:14, 5 December 2012 by Leo (talk | contribs)
This page was last edited on 5 December 2012, at 05:14.

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:

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.