# LINQ: Generate a Cartesian Product

 Tweet
A Cartesian product by definition is a direct product of two sets. Take the following example. Assume you have these two lists:

{A, B, C} and {1, 2, 3}

A Cartesian product of the two lists would be the following:

{(A,1), (A,2), (A,3), (B,1), (B,2), (B,3), (C,1), (C,2), (C,3)}

Let us see how to achieve something similar in LINQ using the SelectMany method

Needless to say, this peice of code is the key to generating cartesian product in LINQ:

```var cartesianLst =
listA.SelectMany(a => listB.Select(b => a + b + ' '));```

using which we are projecting each element of a sequence to an IEnumerable< T> ; projecting to a result sequence, which is the concatenation of the two.

OUTPUT

Also check out Combine Multiple Sequences in LINQ using the Zip Operator - .NET 4.0

Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Anonymous said...

Finally, I found my Cross-Join operation :)

Fabricio Rateni said...

Good article. For those interested in getting the same result using query syntax:

var cartesian2 = from a in listA
from b in listB
select a + b + ' ';

Regards,
Fabricio.

Dinesh Chrysler said...

it can also be done like this,
var l3 = new[] { "A","B", "C" };
var l4 = new[] { 1, 2, 3 };

var output3 = l3.Zip(l4,(Tfirst,Tsecond)=> Tfirst.ToString() + ' ' + Tsecond.ToString()).ToList();
//ouput3: A 1 B 2 C3 are in array list.
string output4 = output3.Aggregate((item1, item2) => item1 + ", " + item2);
//output4 = "A 1, B 2, C 3" are in single string.