Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I take the Cartesian join of two lists in c#?

Tags:

c#

linq

How do I take the Cartesian join of two lists with integers in them?

Can this be done with linq?

like image 603
Vanish Avatar asked Feb 15 '11 14:02

Vanish


3 Answers

Assuming you mean a "cross join" or "Cartesian join":

var query = from x in firstList
            from y in secondList
            select new { x, y }

Or:

var query = firstList.SelectMany(x => secondList, (x, y) => new { x, y });

If you want something else (as you can see from comments, the term "cross product" has caused some confusion), please edit your question appropriately. An example would be very handy :)

like image 93
Jon Skeet Avatar answered Nov 04 '22 18:11

Jon Skeet


For curiosity, another way to accomplish this (which produces the same result as Jon Skeet's answer) is:

firstList.Join(secondList, x => true, y => true, (m, n) => new { m, n });
like image 44
Ross Avatar answered Nov 04 '22 18:11

Ross


If you're not fond of the query syntax (like myself), MoreLINQ provides a method for it that's cleaner, in my opinion:

using MoreLinq;

// ....

firstList.Cartesian(secondList, (x, y) => new { x, y });
like image 3
jpmc26 Avatar answered Nov 04 '22 20:11

jpmc26