
Tuples can be sorted. The Tuple type provides an excellent way to encapsulate units of data, but it can make sorting harder. We use the Sort method on the List type to implement a Tuple sorting delegate.
This C# example program uses the Sort method on a List of Tuples.

First, this program creates a List and adds three new Tuple instances to it. Notice how the Tuple instances store both an int and a string; they could be sorted on either item. Next, we invoke the Sort method on the List: we use the lambda syntax and pass in two arguments (a, b) and return the result of CompareTo in the Item2 property, which is the string.
Tuple Tips Sort List Method Lambda ExpressionProgram that sorts List of Tuple instances [C#]
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<Tuple<int, string>> list = new List<Tuple<int, string>>();
list.Add(new Tuple<int, string>(1, "cat"));
list.Add(new Tuple<int, string>(100, "apple"));
list.Add(new Tuple<int, string>(2, "zebra"));
// Use Sort method with Comparison delegate.
// ... Has two parameters; return comparison of Item2 on each.
list.Sort((a, b) => a.Item2.CompareTo(b.Item2));
foreach (var element in list)
{
Console.WriteLine(element);
}
}
}
Output
(100, apple)
(1, cat)
(2, zebra)Result of the program. You can see that the program changes the ordering of the List so that the Tuples are sorted on their string Item2. If you wanted to sort on the int, you could change the lambda to return a.Item1.CompareTo(b.Item1). Also, you could implement a reverse sort with b.Item2.CompareTo(a.Item2).

There are other ways you can sort Tuples in your C# programs. For example, you can use the LINQ query syntax; this might actually be easiest to remember for some. Check out the LINQ section for more information.
LINQ ExamplesHere, we looked at one way you can sort a List of Tuple instances. The general comparison algorithm and implementation with lambda syntax could be used with other types, such as strings or other objects.
Sort Examples