C# 收集被修改;枚举操作不能执行
我有这段代码,它给我的集合已修改,无法再枚举,但我没有更改值:C# 收集被修改;枚举操作不能执行,c#,C#,我有这段代码,它给我的集合已修改,无法再枚举,但我没有更改值: public static void AddtoDictionary(string words, Dictionary<int, int> dWords) { if (DCache.ContainsKey(words)) { Dictionary<int, int> _dwordCache = DCache[words]; //error right here
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;
}
}
}
}
publicstaticvoidaddtodictionary(字符串、字典dWords)
{
如果(DCache.ContainsKey(字))
{
字典_dwordCache=DCache[words];
//错误就在这里
foreach(int\u key in\u dwordCache.Keys)
{
int _value=_dwordCache[_key];
if(dWords.ContainsKey(_键))
{
dWords[_键]=(dWords[_键]+_值);
}
其他的
{
dWords[\u键]=\u值;
}
}
}
}
我正在更改
dWords
,而没有更改\u dwordCache
。有两本字典。我可以理解,如果我正在更改\u dwordCache
,它将给我该错误,但参数正在更改。您确定在foreach运行时DCache[words]元素未在其他位置修改吗?消除此错误的一种快速而肮脏的方法是转换到不同的列表:
foreach (int _key in _dwordCache.Keys.ToList())
确保文件顶部有“using System.Linq;”
但是如果你有巨大的列表,上面的建议可能会杀死你的程序,一旦你每次调用代码,它就会一次又一次地创建另一个列表
在这种情况下,您可以远离枚举器。尝试将“foreach”替换为:
for(int i=0;i<\u dwordCache.Keys.Count;i++)
{
var key=_dwordCache.ElementAt(i);
}
您确定DCache[words]
没有返回由dWords
引用的同一词典吗?换句话说,即使有两个变量,也可能只有一个字典代码>如果(DCache.ContainsKey(words))是一个清晰的信号,则该行。我想你从缓存中得到的是同一本词典是的,是同一本词典。谢谢。for语句是在90%的其他情况下处理它的方式,但它不能与字典一起使用,它不能实现这个[int i]
(是的,但不是以你想要的方式使用它,它确实是这个[Tkey i]
,在这个问题上i
恰好是int
).ToList()建议有效。但是,是的,第二个建议缺少了一些东西:for(int i=0;i<\u dwordCache.Keys.Count;i++)var key=\u dwordCache.ElementAt(i);
for (int i = 0; i < _dwordCache.Keys.Count; i++)
{
var key = _dwordCache.ElementAt(i);
}