Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update the values while iterating dictionary items?

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?

like image 743
Safran Ali Avatar asked Aug 23 '11 11:08

Safran Ali


People also ask

Can you modify a dictionary while iterating?

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.

Can dictionary values be updated?

The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.

How do you update a list of values in a dictionary?

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')

How do you update multiple values in a dictionary?

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.


1 Answers

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

like image 63
codechkr Avatar answered Nov 15 '22 07:11

codechkr