C Sharp Sort Lists

From Leo's Notes
Revision as of 19:12, 24 February 2017 by Leo (talk | contribs) (Text replacement - "<code>" to "{{code|")
This page was last edited on 24 February 2017, at 19:12.

The correct title of this article is C# Sort Lists.

Suppose that we have an object {{code|Item which contains a few properties such as:

  • Age
  • Name
List<Item> items = new List<Item>();
items.Add(...);

To sort {{code|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 {{code|a.CompareTo(b) method will return a positive value if a > b. When b > a, {{code|a.CompareTo(b) will return a negative value.