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.