列表中的组合(列表(对象))

时间:2014-10-07 21:09:30

标签: .net vb.net list combinations

我有一个包含N个项目的动态列表(SuperList),例如这里有三个项目A,B和C:

Dim A As New List(Of String)
A.Add("Aa")
A.Add("Bb")
A.Add("Cc")

Dim B As New List(Of String)
B.Add("Small")
B.Add("Large")

Dim C As New List(Of Integer)
C.Add(1)
C.Add(2)

Dim SuperList As New List(Of Object)
SuperList.Add(A)
SuperList.Add(B)
SuperList.Add(C)
...

我需要使用以下组合从SuperList生成另一个List(Of List(Of String)):

Aa – Small – 1
Aa – Small – 2
Aa – Large – 1
Aa – Large – 2
Bb – Small – 1
Bb – Small – 2
Bb – Large – 1
Bb – Large – 2
Cc – Small – 1
Cc – Small – 2
Cc – Large – 1
Cc – Large – 2

SuperList中的项目数是动态的。怎么做?

1 个答案:

答案 0 :(得分:4)

您基本上是在尝试计算可变数量列表的笛卡尔积。

这个MSDN article讨论了这个主题,并提出了以下函数(C#代码)

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
{ 
  IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
  return sequences.Aggregate( 
    emptyProduct, 
    (accumulator, sequence) => 
      from accseq in accumulator 
      from item in sequence 
      select accseq.Concat(new[] {item})); 
}

您可以在SuperList上调用该功能。我对VB.NET不好,所以我通过automated converter

运行了这个函数
<System.Runtime.CompilerServices.Extension> _
Private Shared Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))
    Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = New () {Enumerable.Empty(Of T)()}
    Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From accseq In accumulatorFrom item In sequenceaccseq.Concat(New () {item}))
End Function

如果这个&#34;翻译&#34;请更正我是错的。