Comparing and sorting Tuples

suggest change

Tuples can be compared based on their elements.

As an example, an enumerable whose elements are of type Tuple can be sorted based on comparisons operators defined on a specified element:

List<Tuple<int, string>> list = new List<Tuple<int, string>>();
list.Add(new Tuple<int, string>(2, "foo"));
list.Add(new Tuple<int, string>(1, "bar"));
list.Add(new Tuple<int, string>(3, "qux"));

list.Sort((a, b) => a.Item2.CompareTo(b.Item2)); //sort based on the string element

foreach (var element in list) {

// Output:
// (1, bar)
// (2, foo)
// (3, qux)

Or to reverse the sort use:

list.Sort((a, b) => b.Item2.CompareTo(a.Item2));

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents