使用字典的键更新值

Nil*_*h B 8 vb.net vb.net-2010

Dictionary在VB.NET Windows应用程序中使用.

我在a中添加了几个值,Dictionary我想使用它们的键来编辑一些值.

示例:下面我们有一个DATA表,我想将密钥的值 - "DDD"更新为1

AAA - "0"   
BBB - "0" 
CCC - "0' 
DDD - "0"
Run Code Online (Sandbox Code Playgroud)

如何才能做到这一点?

For Each kvp As KeyValuePair(Of String, String) In Dictionary1
    If i = value And kvp.Value <> "1" Then
        NewFlat = kvp.Key.ToString
        ---------------------------------------------
        I want to update set the Value 1 of respective key.
        What should I write here ? 
        ---------------------------------------------
        IsAdded = True
        Exit For
    End If
    i = i + 1
Next kvp
Run Code Online (Sandbox Code Playgroud)

Ňɏs*_*arp 14

如果您知道要更改哪个kvp的值,则不必迭代(for each kvp)字典.将"DDD"/"0"更改为"DDD"/"1":

 myDict("DDD") = "1"
Run Code Online (Sandbox Code Playgroud)

cant use the KeyValuePair its gives error after updating it as data get modified.

如果你试图修改循环中的任何集合For Each,你会得到一个,InvalidOperationException.For Each一旦集合发生变化,枚举器(变量)就变为无效.特别是使用词典,这不是必需的:

Dim col As New Dictionary(Of String, Int32)
col.Add("AAA", 0)
...
col.Add("ZZZ", 0)

Dim someItem = "BBB"
For Each kvp As KeyValuePair(Of String, Int32) In col
    If kvp.Key = someItem Then

        ' A) Change the value?
         vp.Value += 1          ' will not compile: Value is ReadOnly

        ' B) Update the collection?
        col(kvp.Key) += 1
    End If
Next
Run Code Online (Sandbox Code Playgroud)

方法A不会编译,因为KeyValue属性是ReadOnly.
方法B将更改计数/值,但导致异常,Next因为kvp不再有效.

字典有一个内置的方法来为你做所有这些:

If myDict.ContainsKey(searchKey) Then
    myDict(searchKey) = "1"
End If
Run Code Online (Sandbox Code Playgroud)

使用键从字典中获取/设置/更改/删除.