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:
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

{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
No comments:
Post a Comment