更改集合从一个循环内

更改集合从一个循环内

问题描述:

我有一个简单的词典(字符串,对象),我需要遍历并改变在某些条件下的项目。

I have a simple Dictionary(of String, Object) that I need to iterate through and change items depending on some conditions.

正如我不能修改正在通过遍历集合,我怎么做到这一点?

As I can't modify a collection that I'm iterating through, how do I achieve this?

例如,显然是由以下原因引起的无效操作异常

For example, the following obviously causes an Invalid Operation Exception:

Dim mOptions As New Dictionary(of String, Object)
mOptions.Add("optA", "A")
mOptions.Add("optB", "B")
mOptions.Add("optC", "C")

For Each O As KeyValuePair(Of String, Object) In mOptions
    Dim Val As Object = GetSomeOtherObjectBasedOnTheOption(O.Key, O.Value)
    mOptions(O.Key) = Val
Next

无效操作异常
集合已修改;枚举操作可能无法执行。

Invalid Operation Exception
Collection was modified; enumeration operation may not execute.

我想我需要克隆词典第一和遍历副本?什么是这样做的最好方法是什么?

I guess I need to Clone the Dictionary first and iterate over the copy? What's the best way of doing that?

Dim TempOptions As New Dictionary(of String, Object)
For Each O As KeyValuePair(Of String, Object) In mOptions
    TempOptions.Add(O.Key, O.Value)
Next

For Each O As KeyValuePair(Of String, Object) In TempOptions
    Dim Val As Object = GetSomeOtherObjectBasedOnTheOption(O.Key, O.Value)
    mOptions(O.Key) = Val
Next

这闻起来有点虽然。

您可以只遍历的的副本的按键,而不是遍历 KeyValuePair 秒。

You can just iterate over a copy of the keys instead of iterating over the KeyValuePairs.

For Each K as String in mOptions.Keys.ToArray()
   Dim Val As Object = GetSomeOtherObjectBasedOnTheOption(K)
   mOptions(K) = Val
Next

(抱歉,如果你不能只是粘贴在 - 我一般不写VB)

(sorry if you can't just paste that in -- I don't normally write VB)

它没有严格的必须是一个数组:你可以做VB相当于的foreach(在新名单,其中字符串K表;串>(mOptions.Keys))还有,例如。

It doesn't strictly have to be an array: you can do the VB equivalent of foreach (string k in new List<string>(mOptions.Keys)) as well, for instance.

如果您遍历原来的按键,修改你的字典,你会得到同样的错误。

If you iterate over the original keys and modify your dictionary, you'll get the same error.