我在VB.NET Windows应用程序中使用Dictionary
。
我在Dictionary
中添加了几个值,并且我想使用它们的键来编辑一些值。
例子:
下面我们有一个DATA表,我想将键的值“DDD”更新为1
如何才能做到这一点?
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
最佳答案
如果您知道要更改哪个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将不会编译,因为
Key
和Value
属性为ReadOnly。方法B将更改计数/值,但会导致
Next
发生异常,因为kvp
不再有效。词典有一个内置方法可以为您完成所有操作:
If myDict.ContainsKey(searchKey) Then
myDict(searchKey) = "1"
End If
使用键从字典中获取/设置/更改/删除。
关于vb.net - 使用字典键更新值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19539367/