tags:

views:

109

answers:

2

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.

+4  A: 

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;
Tomas Petricek
cool thanks I'm looking forward to upgrading to 4.0 soon
Damian Kennedy
@Damian: This would work in C# 3.0 too, but you'd need to implement your own `Tuple<T1, T2>` (it is just a simple class with two properties of generic types `T1 Item1 { get; set; }` and `T2 Item2 { get; set; }`
Tomas Petricek
+2  A: 

Another way to do it in python is this

from operator import itemgetter
sorted(myList, key=itemgetter(1))
gnibbler
cheers I didn't know about itemgetter
Damian Kennedy