Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's elegant way to rewrite following LINQ statement using extension methods?

Tags:

c#

.net

linq

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?

like image 417
Jakub Šturc Avatar asked Mar 30 '10 09:03

Jakub Šturc


2 Answers

e.SelectMany(x => e.SelectMany(y => e.Select(z => new { x, z })))
like image 57
Darin Dimitrov Avatar answered Oct 20 '22 02:10

Darin Dimitrov


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 })))
like image 26
Jon Skeet Avatar answered Oct 20 '22 00:10

Jon Skeet