iefpw
iefpw

Reputation: 7062

Collection was modified; enumeration operation may not execute

I have this code and it is giving me collection was modified and cannot enumerate anymore, but I wasn't changing the value:

public static void AddtoDictionary(string words, Dictionary<int, int> dWords)
{
    if (DCache.ContainsKey(words))
    {
        Dictionary<int, int> _dwordCache = DCache[words];

        //error right here
        foreach (int _key in _dwordCache.Keys)
        {
            int _value = _dwordCache[_key];

            if (dWords.ContainsKey(_key))
            {
                dWords[_key] = (dWords[_key] + _value);
            }
            else
            {
                dWords[_key] = _value;
            }
        }
    }
}

I'm changing the dWords and not changing _dwordCache. There are two dictionaries. I can understand that if I was changing _dwordCache it will give me that error but the parameter was being changed.

Upvotes: 0

Views: 1622

Answers (2)

Cesar
Cesar

Reputation: 615

A quick and dirty way to blast away this error is converting to a different list:

foreach (int _key in _dwordCache.Keys.ToList())

Make sure you have "using System.Linq;" at the top of your file.

But if you have huge lists, the suggestion above might kill your program, once everytime you call the code, it will create another list again and again.

Then you could be away from enumerators in this case. Try replace your "foreach" by:

for (int i = 0; i < _dwordCache.Keys.Count; i++)
{
    var key = _dwordCache.ElementAt(i);
}

Upvotes: 1

Uzzy
Uzzy

Reputation: 550

Are you sure DCache[words] element is not modified elsewhere while foreach is running?

Upvotes: 0

Related Questions