如何使用列表中的名称创建叉积对象?
How can I create a cross-product object with names from a list?
我有一个包含 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
您可以使用 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
我正在使用 Anonymous Type, Collection Initializers and LINQ。
我有一个包含 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
您可以使用 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
我正在使用 Anonymous Type, Collection Initializers and LINQ。