如何生成多个数组的所有排列/组合?

前端之家收集整理的这篇文章主要介绍了如何生成多个数组的所有排列/组合?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的目标很简单,我正在尝试为数据库中的产品生成所有可能组合的列表.

所以例如;产品选项如下

>产品选项:颜色/值:红色,绿色,蓝色
>产品选项:尺寸/值:小,中,大,XL
>产品选项:风格/价值观:男士,女士

我希望能够自动生成所有3个的每个组合:

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

无论我是否将2,3,4或5个数组传入其中,我都需要该函数.

我已经做了很多研究并且发现了以下文章但却无法实现我的目标.

我找到的文章如下:

> How to Generate Combinations of Elements of a List<T> in .NET 4.0
> vb .net permutation of string. permutation or combination?

在笛卡儿产品上调整 Eric Lippert’s blog代码
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()
    Next
    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)
原文链接:/vb/255563.html

猜你在找的VB相关文章