vb.net 使用列表类和字典的多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23188996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
multidimensional array using list class and dictionary
提问by Liza
//Declaration
//宣言
Dim values As New List(Of Dictionary(Of String, String))()
I am trying to create a multidimensional array. this is my code:
我正在尝试创建一个多维数组。这是我的代码:
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
My error is: The given key was not present in the dictionary.
我的错误是:字典中不存在给定的键。
i want an output like this:
我想要这样的输出:
1 => array(
CostCentre=>10.00
ProcessDescription=>"up"
)
2 => array(
CostCentre=>20.00
ProcessDescription=>"sided"
)
3 => array(
CostCentre=>110.00
ProcessDescription=>"cutted"
)
采纳答案by har07
You have two dictionaries in the list. One of which contains only "CostCentre" key, and the other contains only "ProcessDescription" key. So when you try to access both keys from a dictionary, one key must be missing.
列表中有两本词典。其中一个只包含“CostCentre”键,另一个只包含“ProcessDescription”键。因此,当您尝试从字典中访问两个键时,必须缺少一个键。
You may want to use List(Of Tuple(Of String, String))instead of List(Of Dictionary(Of String, String)). This example works for me :
您可能想要使用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
And for your case, it could be something like this :
对于您的情况,它可能是这样的:
'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

