LINQ: Generate a Cartesian Product

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

LINQ Cartesian

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.


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

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


Anonymous said...

Finally, I found my Cross-Join operation :)

Fabricio 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 + ' ';


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.