Search code examples
c#listlinqcartesian

Get individual items of LINQ Cartesian Product


var A = new[] {A, B}; 
var B = new[] {X, Y, Z}; 
var Product = 
from _A in A 
from _B in B 
select new[] { _A, _B };
//Intent below:
foreach (pair in Product)
{
SomeFunction(pair[0],pair[1])
}

//Output:
SomeFunction(A,X)
SomeFunction(A,Y)
SomeFunction(A,Z)
SomeFunction(B,X)
SomeFunction(A,Y)
SomeFunction(A,Z)

Instead of combining the two lists into one item, how do I retrieve _A & _B as independent variables? So that for each Cartesian cross product combination (A,X..A,Y..A,Z..and so on) I can send them into another function to process?

Ideally, these variables will not be strings so any workarounds with getting character @ indicies will not work.

EDIT: Looks like I was right all along. Thank you for the community for confirming my intent.


Solution

  • I think you're 95% there, and in putting your example together you're 99% there.

    Your query will give you the cartesian product as you desire.

    var A = new[] {A, B}; 
    var B = new[] {X, Y, Z}; 
    var Product = from _A in A 
                  from _B in B 
                  select new[] { _A, _B };
    

    Product is now and IEnumerable<T>. It would look like this:

    [
        [A, X]
        [A, Y]
        [A, Z]
        [B, X]
        [B, Y]
        [B, Z]
    ]
    

    All you need to do now is enumerate it's values, which you have in your intent (though the variable name is wrong):

    //Intent below:
    foreach (pair in Product)
    {
        SomeFunction(pair[0], pair[1]);
    }