Comparing and sorting Tuples
suggest changeTuples 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) {
Console.WriteLine(element);
}
// Output:
// (1, bar)
// (2, foo)
// (3, qux)
Or to reverse the sort use:
list.Sort((a, b) => b.Item2.CompareTo(a.Item2));
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents