嘿,我有大约4个dicionarys持有variuos东西的价值。每个字典对4个字典中的每个字段都有相同的密钥。
示例:
dictionary1 (string, string):
key = 523697777, value = "bobs burgers"
key = 89557, value = "Blah blah 1"
key = 598823644, value = "something"
dictionary2 (string, string):
key = 523697777, value = "oats and honey"
key = 89557, value = "juicyfruit"
key = 598823644, value = "sun glasses"
dictionary3 (string, datetime):
key = 523697777, value = 01/05/2013 00:00:00
key = 89557, value = 01/24/2013 00:00:00
key = 598823644, value = 03/12/2013 00:00:00
dictionary4 (string, string):
key = 523697777, value = "Computers"
key = 89557, value = "IM"
key = 598823644, value = "cans"
现在我希望能够循环并从每个dicionary获取正确的值,而不必遍历每个dicionary seprate。
Currenly我这样做:
Dim allTogether As New StringBuilder
For Each dict1 In dictionary1
For Each dict2 In dictionary2
If dict1.Key = dict2.Key Then
allTogether.Append(dict1.Value)
allTogether.Append(dict2.Value)
For Each dict2 In dictionary3
If dict2.Key = dict3.Key Then
allTogether.Append(dict3.Value)
For Each dict2 In dictionary3
If dict3.Key = dict4.Key Then
allTogether.Append(dict4.Value)
End If
Next
End If
Next
End If
Next
Next
应该产生:
bobs burgers oats and honey 01/05/2013 00:00:00 Computers
Blah blah 1 juicyfruit 01/24/2013 00:00:00 IM
something sun glasses 03/12/2013 00:00:00 cans
是否可以一举获取数据?
答案 0 :(得分:3)
获取钥匙:
Dim keys = dictionary1.Keys
迭代他们:
For Each key In Keys
构造结果(此处:打印到控制台):
Console.WriteLine("{0} {1} {2} {3}",
dictionary1(key),
dictionary2(key),
dictionary3(key),
dictionary4(key))
结束循环。
Next
答案 1 :(得分:0)
此外,如果键一直存在于所有四个词典中,那么作为建议,为什么不:
Public Structure myStruct
Public thing1 As String
Public thing2 As String
Public dateThing As DateTime
Public thing3 As String
End Structure
Private myDictionary As Dictionary(Of String, myStruct)
如果不保证在所有词典中都使用相同的键,为什么不使用词典的功能呢?
If dictionary1.ContainsKey(someKey) Then allTogether.Append(dictionary1(someKey))
等
答案 2 :(得分:0)
这应该有用 - 如果你仍然需要使用stringbuilder。
For Each sKey In Dictionary1.Keys
allTogether.Append(Dictionary1(sKey))
allTogether.Append(Dictionary2(sKey))
allTogether.Append(Dictionary3(sKey))
allTogether.Append(Dictionary4(sKey))
allTogether.Append("---------------")
Next
我最后添加了“--------------”作为集合之间的分隔符。