Update Dictionary value based on Key matching

I am trying to update dictionary values based on search operation done on Dictionary key.

when i print default values of Dictionary using for each, it prints well.
but when i update the value of keys, then i get error as.

collection was modified enumeration operation may not execute on second run.



are you doing a ForEach on a dictionary with TypeArgument = KeyValuePair (x, y)?

PS: when you have an Exception window, you have a link “copy to clipboard”. you can then paste it in your post.

1 Like

my dictionary is ShareList (Of String, int)

For what I see, you might be better with a Dictionary(Of String, Decimal) and assign Convert.ToDecimal(currentPrice)

Iterate over SharedList.Keys.ToArray

1 Like

Any idea why typecasting should give that error ?

I tried to debug. 1st set is getting updated . But when for each is reached again. I get the error.

Sorry, I edited my message after your other posts

You should Iterate over SharedList.Keys.ToArray

EDIT: add missing s

You are suggesting me to use the key list as array for iteration whereas there is no problem in iteration of the Dictionary.

for example:
image is executed fine printing the highlighted section on output.
followed by the current price. So, for each iteration on Dictionary works fine, the only problem is update of values.

Please try to understand the problem, its not iteration it is update then iteration.
I tried with Dictionary (of String, String)
Still no luck

Have you tried it?

I’m suggesting you to use a copy of the key list as array for iteration. Your error is that ShareList.Keys is an interface over the very same object your modifying. As soon as the underlying object change, it is no longer valid.

The array produced won’t care if the dictionary has changed. Try to understand that.

1 Like

Okay got it, i will give it a try

Yes, it means that we must not iterate as well as try to modify the same Dictionary set we are iterating.
thanks the solution worked.

1 Like

I want to mark your answer as solution , can you please explain in simple words as i did.
this is techy for new learners.
I will mark that as answer.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.