What is the default behavior when sorting a list of tuples?

I want to sort List

from Tuple<int, string>

using value int

. This example uses the following code:

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"));

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

foreach (var element in list)
{
    Console.WriteLine(element);
}

      

I noticed that if I changed the following line:

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

      

in

list.Sort();

      

the items are sorted again.

Does this mean the default is the first item? If so, is there a performance difference between the two methods?

+3


source to share


1 answer


Tuples compare themselves by comparing each component in turn , using the default collation for that component. It's not very clear, but ( from MSDN ):

The method Tuple<T1, T2>.IComparable.CompareTo

uses the default object mapping to compare each component.



This is slightly different from your example, as the sort will continue until 2nd, 3rd, 4th, etc. tuple components ( string

in your case) in case of matches (2 elements with int

7

, for example)

+5


source







All Articles