通过键

时间:2016-07-28 07:02:01

标签: .net vb.net collections concurrentdictionary

我有一个ConcurrentDictionary我要添加元素。

密钥不是唯一的,可能会反映多个值。

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

    附加信息:从字符串"洛杉矶转换"输入'整数'无效。

    所以,如果我有一个键(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
    

1 个答案:

答案 0 :(得分:0)

传递给dict.Values(int)方法的参数是元素的索引,而不是键。如果要按ist键添加值,请使用

For Each values In dict(stKeys)

然而,正如Jehof在他的评论中已经提到的那样,你不可能拥有一个非独特键的ConcurrentDictionary。它只会添加第一个元素,其他调用将失败。