Menus

Tuesday, December 4, 2012

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.

OUTPUT

LINQ SelectMany

No comments:

Post a Comment