//申报
Dim values As New List(Of Dictionary(Of String, String))()
我正在尝试创建一个多维数组。这是我的代码:
con.Open()
ccsfreader = ccsfcomm.ExecuteReader
ccsfreader.Read()
If ccsfreader.HasRows Then
Do
values.Add(New Dictionary(Of String, String)() From {{"CostCentre", ccsfreader.Item("CostCentre")}})
values.Add(New Dictionary(Of String, String)() From {{"ProcessDescription", ccsfreader.Item("ProcessDescription")}})
Loop While ccsfreader.Read()
End If
con.Close()
For Each value As Dictionary(Of String, String) In values
Dim CostCentre As String = value("CostCentre")
Dim ProcessDescription As String = value("ProcessDescription")
cmblaborcost.Items.Add(CostCentre)
Next
我的错误是:字典中不存在给定的关键字。
我想要这样的输出:
1 => array(
CostCentre=>10.00
ProcessDescription=>"up"
)
2 => array(
CostCentre=>20.00
ProcessDescription=>"sided"
)
3 => array(
CostCentre=>110.00
ProcessDescription=>"cutted"
)
列表中有两个字典。其中一个只包含"CostCentre"键,另一个只包括"ProcessDescription"键。因此,当您尝试访问字典中的两个键时,必须缺少一个键。
您可能希望使用List(Of Tuple(Of String, String))
而不是List(Of Dictionary(Of String, String))
。这个例子适用于我:
Dim values As New List(Of Tuple(Of String, String))
values.Add(Tuple.Create("a1", "a2"))
values.Add(Tuple.Create("b1", "b2"))
values.Add(Tuple.Create("c1", "c2"))
'generate array from List of Tuple'
Dim result = values.Select(Function(x) New String() {x.Item1, x.Item2}).ToArray()
For Each s As String() In result
Console.WriteLine(s(0) & ", " & s(1))
Next
对于你的情况,它可能是这样的:
'example to add item to list'
Dim values As New List(Of Tuple(Of String, String))
......
If ccsfreader.HasRows Then
Do
'values.Add(Tuple.Create(ccsfreader.Item("CostCentre"), ccsfreader.Item("ProcessDescription"))'
values.Add(New Tuple(Of String, String)(ccsfreader.Item("CostCentre"), ccsfreader.Item("ProcessDescription")))
Loop While ccsfreader.Read()
End If
.......
'example to access item from list'
For Each value As Tuple(Of String, String) In values
Dim CostCentre As String = value.Item1
Dim ProcessDescription As String = value.Item2
cmblaborcost.Items.Add(CostCentre)
Next