C Sharp Sort Lists

From Leo's Notes
Last edited on 24 February 2017, at 19: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:

// 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.