How to update values ​​when repeating dictionary items?

I have a dictionary:

Dictionary<string, long> Reps = new Dictionary<string, long>(); 

and I want to update values ​​during iteration over all elements, for example:

 foreach (string key in Reps.keys) { Reps[key] = 0; } 

he gives me an error saying:

 "Collection was modified; enumeration operation may not execute" 

can someone tell me why it gives me this error, because I have another function that adds a value, and it is called when the button is clicked:

 public static void Increment(string RepId, int amount) { long _value = Convert.ToInt64(Reps[RepId]); _value = _value + amount; Reps[RepId] = _value; } 

and this function works fine. so what's the problem of updating all values? And what is the solution for this?

+6
source share
3 answers

more simplified, do the following:

 foreach (string key in Reps.keys.ToList()) { Reps[key] = 0; } 

and the cause of the error is that you are trying to edit the actual object that is being used, and if you make a copy of it, then use it like this:

 var repscopy = Reps; foreach (string key in repscopy.keys) { Reps[key] = 0; } 

it will give the same error as pointing to the original object, and when ToList () is added, it creates a new List object

+4
source

The problem is not updating the values, you simply cannot change the collection on which your foreach () is based, while foreach iterates over.

Try to do something like this

 List<string> keylist = Reps.keys.ToList(); foreach(string r in keylist) { Reps[r] = 0; } 

it will work.

+4
source

This is because you are changing the element in Dictionary<string, long> , tracing it with foreach . Try it.

 foreach (string key in Reps.Keys.ToList()) { Reps[key] = 0; } 

Now you iterate over the list created using the dictionary. Since this is not a modified original collection, the error will disappear.

+3
source

Source: https://habr.com/ru/post/895666/


All Articles