从多个数组生成所有可能的组合(C#/ VB.NET)

我有n个数组,每个数组可能包含n个元素。 我必须通过从每个数组中获取一个元素来生成所有可能的值组合。

我需要C#/ VB.NET语言的帮助。

以下是一个例子。

Arr1:(a,b,c)Arr2:(1,2)Arr3:(x,y,z)

我希望组合为(将有3 * 2 * 3 = 18种组合)a1x a1y a1z a2x a2y a2z b1x b1y b1z b2x b2y b2z c1x c1y c1z c2x c2y c2z

如果我有4个arrays,将有36个组合。 Arr1:(a,b,c)Arr2:(1,2)Arr3:(x,y,z)Arr4:(m,n)

组合:

a1xm a1xn a1ym a1yn a1zm a1zn …… …… …… …… …… …… ……

根据Eric Lippert撰写的文章

void Main() { var set1 = new object[]{'a', 'b', 'c'}; var set2 = new object[]{1,2,}; var set3 = new object[]{'x', 'y', 'z'}; string.Join(", ", new[] {set1, set2, set3}.CartesianProduct().Select(item => item.ToArray()).Select(item => string.Format("({0},{1},{2})", item[0], item[1], item[2]))).Dump(); } public static class CartesianProductContainer { public static IEnumerable> CartesianProduct(this IEnumerable> sequences) { IEnumerable> emptyProduct = new[] { Enumerable.Empty() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from accseq in accumulator from item in sequence select accseq.Concat(new[] {item})); } } 

输出:

 (a,1,x), (a,1,y), (a,1,z), (a,2,x), (a,2,y), (a,2,z), (b,1,x), (b,1,y), (b,1,z), (b,2,x), (b,2,y), (b,2,z), (c,1,x), (c,1,y), (c,1,z), (c,2,x), (c,2,y), (c,2,z) 

第一种方法

您可以使用嵌套For循环

 for (int i=0; i < Arr1.Length ; i++) { for (int j=0; i < Arr2.Length ; j++) { like this.............. } } 

第二种方法

C# - 迭代多个数组/列表的最有效方法