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.
DCache[words]
isn't returning the same dictionary referenced bydWords
? In other words, even though you have two variables, maybe you only have one dictionary. – Michael Liuforeach
loop, execute this code and tell me the result:var same = Object.ReferenceEquals(_dwordCache, dWords);
– Daniel Hilgarthif (DCache.ContainsKey(words))
is a clear signal. I think you are getting the same dictionary out from the cache – Steve