Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default behaviour when list of tuples is sorted?

I want to sort a List of Tuple<int, string> using the int value. In this example the following code is used:

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

to:

list.Sort();

the elements are again sorted.

Does this mean that the default behaviour is to use the first item? If yes, is there any performance difference between the two techniques?

like image 452
gotqn Avatar asked Jan 05 '15 14:01

gotqn


1 Answers

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

The Tuple<T1, T2>.IComparable.CompareTo method uses the default object comparer to compare each component.

This is slightly different to your example, as the sort will continue to the 2nd, 3rd, 4th etc component of the tuple (the string in your case) in the case of matches (2 items with int of 7, for example)

like image 61
Marc Gravell Avatar answered Oct 30 '22 20:10

Marc Gravell