9

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
4

2 回答 2

17

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

 myDict("DDD") = "1"

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

方法 A 不会编译,因为KeyValue属性是只读的。方法 B 将更改计数/值,但由于不再有效
而导致异常。Nextkvp

字典有一个内置方法可以为您完成所有这些工作:

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

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

于 2013-10-23T12:59:43.340 回答
0

有时您确实想对字典中的每个项目做一些事情。例如,我使用字典来存储相当大的数据结构,仅仅是因为从一个巨大的堆中抓取我的数据似乎几乎是瞬时的,即使字典看起来是 40MB 的 RAM。

例如:

dim col as new dictionary (of string, myStructData)

dim colKeys() as string = col.keys.toArray()
for each colKey in colKeys
  dim tempVal as new myStructData= col(colKey)
  'do whatever changes you want on tempVal
  col(colKey)=tempVal
next colKey

因为您没有更改要枚举的内容,所以不会引发异常。当然,如果出现其他问题并弄乱了您的数据,那么您要么不会遍历所有内容,要么不会在集合中找到关键,这取决于发生了什么。我只在我自己的机器上写这种东西来进行繁重的处理。

于 2017-10-03T17:59:26.597 回答