Matth3w Matth3w - 4 months ago 21
Vb.net Question

Iterating through ConcurrentDictionary values by key

I have a ConcurrentDictionary that I am adding elements to.

The key is not unique, and may reflect multiple values.


  1. I iterate through the keys to get the unique names of them

  2. I iterate through the values by key to get a list of the values

  3. The compiler crashes on the "Next" statement with the following error:




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


So, if I have a key(of String), how can I get the values associated with that key?

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


UPDATE: How I solved the problem:

I used a list, passing a structure to it, with locking instead of a ConcurrentDictionary, and at the end of that, I sorted those items into a NameValueCollection, like so:

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

Answer

The Parameter that is passed to the dict.Values(int) method is the index of the element, not the key. If you want to adress the value by ist key, use

For Each values In dict(stKeys)

However, as Jehof already mentioned in his comment, you can't have a ConcurrentDictionary wit ha non-unique key. It will only add the first element, the other calls will fail.

Comments