I have a dictionary:
Dictionary<string, long> Reps = new Dictionary<string, long>();
and I want to update the values while iterating through all items, like this:
foreach (string key in Reps.keys)
{
Reps[key] = 0;
}
it is giving me an error saying:
"Collection was modified; enumeration operation may not execute"
can anyone tell me why it is giving me this error, because I have one more function that adds the value, and it is called when 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 is working fine. so whats the problem when updating all the values? And whats the solution for this?
To modify a Python dict while iterating over it, we can use the items method to get the key and value. to loop through the key value pairs in t with t. items() and the for loop. In it, we set t2[k] to the prefix + v where v is the value in the t dict.
The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.
Method 1: Using append() function The append function is used to insert a new value in the list of dictionaries, we will use pop() function along with this to eliminate the duplicate data. Syntax: dictionary[row]['key']. append('value')
Update values of multiple keys in a dictionary using update() function. If we want to update the values of multiple keys in the dictionary, then we can pass them as key-value pairs in the update() function.
more simplified, do this:
foreach (string key in Reps.keys.ToList())
{
Reps[key] = 0;
}
and the reason for the error is you are trying to edit the actual object which is in use and if you make a copy of it and then use it like this:
var repscopy = Reps;
foreach (string key in repscopy.keys)
{
Reps[key] = 0;
}
it'll give the same error as it also pointing to the original object, and when the ToList() is added it created a new object of List
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With