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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With