TAGS :Viewed: 9 - Published at: a few seconds ago

[ How to sort a list by the 2nd tuple element in python and C# ]

I had a list of tuples where every tuple consists of two integers and I wanted to sort by the 2nd integer. After looking in the python help I got this:

sorted(myList, key=lambda x: x[1])

which is great. My question is, is there an equally succinct way of doing this in C# (the language I have to work in)? I know the obvious answer involving creating classes and specifying an anonymous delegate for the whole compare step but perhaps there is a linq oriented way as well. Thanks in advance for any suggestions.

Answer 1


Another way to do it in python is this

from operator import itemgetter
sorted(myList, key=itemgetter(1))

Answer 2


Assuming that the list of tuples has a type IEnumerable<Tuple<int, int>> (a sequence of tuples represented using Tuple<..> class from .NET 4.0), you can write the following using LINQ extension methods:

var result = myList.OrderBy(k => k.Item2);

In the code k.Item2 returns the second component of the tuple - in C#, this is a property (because accessing item by index wouldn't be type-safe in general). Otherwise, I think that the code is pretty succinct (also thanks to nice lambda function notation).

Using the LINQ query syntax, you could write it like this (although the first version is IMHO more readable and definitely more succinct):

var result = from k in myList orderby k.Item2 select k;