C Sharp Sort Lists

From Leo's Notes
Revision as of 05:11, 5 December 2012 by Leo (talk | contribs) (Created page with "{{Correct title|C# Sort Lists|reason=#}} Suppose that we have an object <code>'''Item'''</code> which contains a few properties such as: * Age * Name List<Item> items = new...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
This page was last edited on 5 December 2012, at 05:11.

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.