Joe Raio Joe Raio - 1 year ago 78 Question

How can I generate all permutations / combinations of multiple arrays?

My goal is simple, I am trying to generate a list of all possible combinations for a product in a database.

So for example; the product options are as follows

  • Product Option: Color / Values: Red, Green, Blue

  • Product Option: Size/ Values: Small, Med, Large, XL

  • Product Option: Style / Values: Men, Women

I want to be able to auto generate every single combination of all 3:

Small, Red, Mens
Small, Green, Mens
Small, Blue, Mens

I need the function to work whether I pass 2,3,4 or 5 arrays into it.

I've done quite a bit of research and came across the following articles but have been unable to accomplish my goal.

The articles I found are as follows:

Answer Source

Adapting code from Eric Lippert's blog on Cartesian products:

Private Function CartesianProduct(Of T)(ParamArray sequences As T()()) As T()()

    ' base case: 
    Dim result As IEnumerable(Of T()) = {New T() {}}
    For Each sequence As var In sequences
        Dim s = sequence
        ' don't close over the loop variable 
        ' recursive case: use SelectMany to build the new product out of the old one 
        result = From seq In result
                 From item In s
                 Select seq.Concat({item}).ToArray()
    Return result.ToArray()
End Function


Dim s1 As String() = New String() {"small", "med", "large", "XL"}
Dim s2 As String() = New String() {"red", "green", "blue"}
Dim s3 As String() = New String() {"Men", "Women"}

Dim ss As String()() = CartesianProduct(s1, s2, s3)