tags:

views:

124

answers:

2

I have following LINQ statement and I want to rewrite it using extension methods.

from x in e
from y in e
from z in e
select new { x, z }

One possible solution is:

e.Join(e, x => 42, y => 42, (x, y) => new { x, y })
  Join(e, _ => 42, z => 42, (_, z) => new { _.x, z }); 

However this is everything but elegant.

Do you any idea how to improve beauty of second expression?

+3  A: 

Using Join is the wrong approach IMO.

The direct equivalent of this is (I think!):

e.SelectMany(x => e.SelectMany(y => e.Select(new { y, z }),
             (x, yz) => new { x, yz.z })

Although I think it would be equivalent to:

e.SelectMany(x => e.SelectMany(y => e.Select(new { x, z }));
Jon Skeet
In the sense of beauty `Join` is clearly wrong approach. In the sense of correctness relational algebra (SQL) intuition tells me that this should be fine.
Jakub Šturc
@Jakub: It might work, but that doesn't make it the right approach. The LINQ equivalent of a cross-join (i.e. where there are no "keys" as such) isn't `Join`, it's `SelectMany`) - even though `SelectMany` itself provides more functionality than this.
Jon Skeet
+5  A: 
e.SelectMany(x => e.SelectMany(y => e.Select(z => new { x, z })))
Darin Dimitrov