我正在尝试搜索字典以查看它是否具有特定值,如果有则更改它。 这是我的代码:
foreach (var d in dictionary)
{
if (d.Value == "red")
{
d.Value = "blue";
}
}
在 Visual Studio 中,当我单步调试代码时,我可以看到它更改了值,然后当它遇到 foreach 循环再次重申时,它会抛出异常
"Collection was modified; enumeration operation may not execute"
我该如何解决这个问题?
最佳答案
您无法在 foreach 中间更改它 - 您需要想出一些其他机制,例如:
// Get the KeyValuePair items to change in a separate collection (list)
var pairsToChange = dictionary.Where(d => d.Value == "red").ToList();
foreach(var kvp in pairsToChange)
dictionary[kvp.Key] = "blue";
关于c# - 在 C# 中使用字典时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15527900/