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
That smells a bit though.
You can just iterate over a copy of the keys instead of iterating over the
KeyValuePairs.(sorry if you can’t just paste that in — I don’t normally write VB)
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.