Updating Value using key of the dictionary

Nilesh B picture Nilesh B · Oct 23, 2013 · Viewed 36.2k times · Source

I am using a Dictionary in VB.NET Windows application.

I have added several values in a Dictionary and I want to edit some values using their key.

Example: Below we have a DATA table and I want to update the value of the key - "DDD" to 1

AAA - "0"   
BBB - "0" 
CCC - "0' 
DDD - "0"

How can this be done?

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

Answer

Ňɏssa P&#248;ngjǣrdenlarp picture Ňɏssa Pøngjǣrdenlarp · Oct 23, 2013

If you know which kvp's value you want to change, you do not have to iterate (for each kvp) the dictionary to so. to Change "DDD"/"0" to "DDD"/"1":

 myDict("DDD") = "1"

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

If you try to modify any collection in a For Each loop, you'll get a, InvalidOperationException. The enumerator (the For Each variable) becomes invalid once the collection changes. Especially with a Dictionary, this is not needed:

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

Method A wont compile because the Key and Value properties are ReadOnly.
Method B will change the count/Value, but result in the Exception on Next because kvp is no longer valid.

Dictionaries have a built in method to do all that for you:

If myDict.ContainsKey(searchKey) Then
    myDict(searchKey) = "1"
End If

Use the key to get/set/change/remove from the dictionary.