0

嘿,我有大约 4 个持有各种价值的字典。每个字典对于 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"

现在我希望能够循环并从每个字典中获取正确的值,而不必循环遍历每个字典。

目前我正在这样做:

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

是否可以一键获取数据?

4

3 回答 3

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
于 2013-08-30T17:57:27.510 回答
0

This should work - if you still need to use 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

I've added last "--------------" as separator between sets.

于 2013-08-30T18:05:50.200 回答
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))

等等

于 2013-08-30T18:00:17.910 回答