0
votes

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.

2
Are you sure DCache[words] isn't returning the same dictionary referenced by dWords? In other words, even though you have two variables, maybe you only have one dictionary.Michael Liu
Before the foreach loop, execute this code and tell me the result: var same = Object.ReferenceEquals(_dwordCache, dWords);Daniel Hilgarth
This line if (DCache.ContainsKey(words)) is a clear signal. I think you are getting the same dictionary out from the cacheSteve
Yes it was same dictionary. Thanks.iefpw

2 Answers

1
votes

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);
}
0
votes

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