我有一个n个数据列的列表的内存表示
Dim l As New List(Of KeyValuePair(Of String, List(Of Double)))
例如
Column 1: {1, 2, 3, 4, 5}
Column 2: {-0.05, 0, 450.7}
etc.
我需要交叉连接,采用笛卡尔积,或者您喜欢的任何术语,整个列表,保留名称,并将结果存储到对象中。结果看起来像
Col 1 Col 2
1 -0.05
1 0
1 450.7
2 -0.05
2 0
2 450.7
3 -0.05
(etc.)
如何做到这一点?
更新
以下答案适用于C#。对于后人来说,这是VB.Net的等价物(应归功于作者)
Private Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))
Dim result As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}
For Each sequence In sequences
Dim s = sequence
result = From seq In result
From item In s
Select seq.Concat({item})
Next
Return result
End Function
答案 0 :(得分:2)
您可以使用LINQ
Dim c1 = New List(Of Integer) From {1, 2, 3, 4, 5}
Dim c2 = New List(Of Double) From {-0.05, 0, 450.7}
Dim product = From first In c1 From second In c2 Select New With {first, second}
For Each x In product
Console.WriteLine(x)
Next
Console.ReadKey()
如果你需要获得超过2列的笛卡尔积,这里有一篇Eric Lippert关于这个主题的文章(C#):Computing a Cartesian product with LINQ