按键遍历 ConcurrentDictionary 值

Iterating through ConcurrentDictionary values by key

我有一个要向其中添加元素的 ConcurrentDictionary。

键不唯一,可能反映多个值。

  1. 我遍历键以获取它们的唯一名称
  2. 我按键遍历值以获取值列表
  3. 编译器在 "Next" 语句上崩溃并出现以下错误:

Additional information: Conversion from string "LOS ANGELES" to type 'Integer' is not valid.

那么,如果我有一个(字符串的)键,我怎样才能获得与该键关联的值?

    Dim dict As New ConcurrentDictionary(Of String, String)
    dict.TryAdd("LOS ANGELES", "black")

    dict.TryAdd("LOS ANGELES", "yellow")
    dict.TryAdd("LOS ANGELES", "blue")
    dict.TryAdd("LOS ANGELES", "orange")
    dict.TryAdd("LOS ANGELES", "yellow")
    dict.TryAdd("LOS ANGELES", "yellow")
    dict.TryAdd("LOS ANGELES", "yellow")
    dict.TryAdd("LOS ANGELES", "yellow")
    dict.TryAdd("LOS ANGELES", "orange")


    For Each stKeys As String In dict.Keys
        If stKeys <> Nothing Then
            For Each values In dict.Values(stKeys)
                If values <> Nothing Then
                       Debug.Print(values.ToString)
                End If
            Next
        End If
    Next

更新:我是如何解决这个问题的:

我使用了一个列表,将结构传递给它,使用锁定而不是 ConcurrentDictionary,最后,我将这些项目分类到 NameValueCollection 中,如下所示:

Structure structCities
          CityName as String
          vColor as string
End Structure

DIM dataList as new List(of structCities)
DIM vData as new structCities

with vData
     .CityName = "LOS ANGELES"
     .vColor = "black"
end with: dataList.add(vData)

with vData
     .CityName = "LOS ANGELES"
     .vColor = "black"
end with: dataList.add(vData)

with vData
     .CityName = "LOS ANGELES"
     .vColor = "black"
end with: dataList.add(vData)

with vData
     .CityName = "LOS ANGELES"
     .vColor = "black"
end with: dataList.add(vData)

with vData
     .CityName = "LOS ANGELES"
     .vColor = "yellow"
end with: dataList.add(vData)

Dim dict As New NameValueCollection
For Each c In dataList 
       dict.Add(c.CityName, c.vColor)
Next

传递给dict.Values(int) 方法的参数是元素的索引,而不是键。如果你想通过 ist key 来寻址值,使用

For Each values In dict(stKeys)

但是,正如 Jehof 在他的评论中已经提到的,您不能拥有具有非唯一键的 ConcurrentDictionary。它只会添加第一个元素,其他调用将失败。