views:

130

answers:

2

How can this LINQ query expression be re-expressed with extension method calls?

public static List<Tuple<int, int>> Concat()
{
    return (from x in Enumerable.Range(1, 3)
           from y in Enumerable.Range(4, 3)
           select new Tuple<int, int>(x, y)).ToList();
}
+8  A: 
return Enumerable.Range(1, 3).SelectMany(x => Enumerable.Range(4, 3)
           .Select(y => new Tuple<int, int>(x, y))).ToList();

Your version looks more readable :-)

Darin Dimitrov
+1  A: 
Enumerable.Range(1, 3).SelectMany(
    i => Enumerable.Range(4, 3),
    (i, j) => new Tuple<int, int>(i, j)
).ToList();
Jason
Using the overloaded SelectMany with a resultSelector function seams more readable to me. Given that this is a translation of my Haskell list comprehension [(x,y)|x<-[1,2,3],y<-[4,5,6]].
robertz
This example of can be written more concisely using the point-free style.(See http://en.wikipedia.org/wiki/Point-free_programming)Enumerable.Range(1, 3).SelectMany( i => Enumerable.Range(4, 3), Tuple.Create).ToList();
robertz