我有一個我正在向其中添加元素的ConcurrentDictionary。通過密鑰對ConcurrentDictionary值進行迭代
關鍵不是唯一的,並可能反映多個值。
- 我通過按鍵進行迭代,讓他們的唯一的名稱
- 我通過鍵的值重複,以獲得與下面的「下一步」語句值
- 編譯器崩潰的列表錯誤:
Additional information: Conversion from string "LOS ANGELES" to type 'Integer' is not valid.
所以,如果我有(一個String)的關鍵,我怎麼能得到與該鍵關聯的值?
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
你的代碼將只存儲字典中的第一項(洛杉磯,「黑色」)。所有其他對'TryAdd'的調用將返回'false',因爲關鍵的LOS ANGELES已經存在。 – Jehof
事情是,它不只是存儲第一個值。當你把鼠標放在dict.values()上時,它會返回每個值,但沒有問題,但是你說的鍵必須是唯一的。 – Matth3w
所以你從ConcurrentDictionary(帶有非唯一鍵)到List? – Paparazzi