2

I have a dynamic list (SuperList) with N items, for example here with three items A, B and 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)
...

I need to generate from SuperList another List(Of List (Of String)) with these combinations:

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

The number of items in SuperList is dynamic. How to do that?

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
milos
  • 103
  • 1
  • 11
  • possible duplicate of [How to "zip" or "rotate" a variable number of lists?](http://stackoverflow.com/questions/17976823/how-to-zip-or-rotate-a-variable-number-of-lists) – Cᴏʀʏ Oct 07 '14 at 21:46

1 Answers1

4

You are basically trying to calculate the cartesian product of a variable number of lists.

This MSDN article discusses the topic and comes up with the following function (C# code)

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})); 
}

You would call that function on SuperList. I'm bad at VB.NET so I ran the function through an 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

Please correct me if this "translation" is wrong.

dee-see
  • 23,668
  • 5
  • 58
  • 91
  • Yes I need to use SuperList "structure". I know your solution, but this is usable only if I have known number of items in SuperList. But I need solution for unknown dynamic number of items. – milos Oct 07 '14 at 21:30
  • Oh ok, I misunderstood by dynamic that the number of items in `A`, `B` and `C` could vary. I'll try to think of something. – dee-see Oct 07 '14 at 21:31