循环访问字典并删除字典条目时出错'Collection was modified; enumeration operation may not execute.'



我正在遍历字典,我想尝试从字典中删除某些不需要的键。

我的代码如下

foreach (KeyValuePair<string, string> stackOfItems in ItemStack)
{
string Name = stackOfItems .Key;
string Price= stackOfItems .Value;
if (listOfSelectedOldItems.Contains(Name))
{
ItemStack.Remove(Name);
}
}

我要做的就是删除字典条目(键和值(,如果某个键在列表中。完整错误:- System.InvalidOperationException: '集合已修改;枚举操作可能无法执行。

谁能帮我解决这个问题

这是因为foreach使用枚举器,并且在删除项目时它变得无效。

您可以构建要删除的项目列表,并在第二步中执行实际删除。

var keysToRemove = new List<string>();
foreach (var stackOfItems in ItemStack)
{
string Name = stackOfItems.Key;
string Price= stackOfItems.Value;
if (listOfSelectedOldItems.Contains(Name))
{
keysToRemove.Add(Name);
}
}
foreach (var key in keysToRemove)
{
ItemStack.Remove(key);
}

更新

正如 canton7 所说,您可以简单地尝试删除listOfSelectedOldItems中的所有项目。

foreach (var key in listOfSelectedOldItems)
{
ItemStack.Remove(key);
}

最新更新