2013-10-23 53 views
2

我在VB.NET Windows应用程序中使用Dictionary使用字典的键更新值

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

例子: 下面我们有一个数据表,我想关键的值更新 - “DDD” 1

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

如何才能做到这一点?

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 
+0

无法使用KeyValuePair,在数据被修改后更新它时会给出错误。 –

+0

如果你正确地解释你的确切条件(输入+你想得到的),我相信Tim或者我可以提供一个完全符合你想要的代码。请重点关注一个问题并删除另一个问题,下次如果您的问题没有得到妥善解决,您应考虑选择询问(或更好地解释您的问题),而不是发布新问题。 – varocarbas

回答

9

如果你知道你要更改的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将更改计数/值,但在Next上会导致异常,因为kvp不再有效。

字典有一个内置的方法做一切你:

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

使用键的get/set /变更/从字典中删除。

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 

因为你不改变你列举了什么,在没有抛出异常。当然,如果有其他事情出现并弄乱了你的数据,那么你要么不会遍历所有的东西,要么根本不会在集合中找到关键字,这取决于发生了什么。我只在自己的机器上写这类东西来重处理。

+0

这似乎没有回答如何编辑给定键的值的问题。这是如何编辑给定所有键的所有值。 –