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
Also check out Combine Multiple Sequences in LINQ using the Zip Operator - .NET 4.0

3 comments:

  1. Finally, I found my Cross-Join operation :)

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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.

    ReplyDelete