收集被修改;枚举操作可能无法执行

时间:2013-05-04 16:38:15

标签: c#

我有这个代码,它给我的集合已修改,不能再枚举,但我没有更改值:

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;
            }
        }
    }
}

我正在更改dWords而不是更改_dwordCache。有两本词典。我可以理解,如果我要更改_dwordCache,它会给我错误,但参数正在更改。

2 个答案:

答案 0 :(得分:1)

快速而肮脏的方法来消除此错误正在转换为另一个列表:

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

确保您“使用System.Linq;”位于文件顶部。

但如果您有大量列表,上面的建议可能会导致您的程序失效,每次调用代码时,它都会一次又一次地创建另一个列表。

在这种情况下,你可能会远离普查员。尝试通过以下方式替换“foreach”:

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

答案 1 :(得分:0)

你确定在foreach运行的时候,其他地方没有修改DCache [words]元素吗?