如前所述,您想要做的事情是不可能的。但是,另一种解决方案是简单地维护一个标记为删除的项目列表,然后删除这些后记。我也会选择一个foreach而不是一个while循环,更少的代码,例如
var removeList = new List<decimal>();
foreach (var item in myDictionary)
{
// have a condition which indicates which items are to be removed
if (item.Key > 1)
{
removeList.Add(item.Key);
}
}
或者,如果您只是尝试检索要删除的项目,请使用 LINQ
var removeList = myDictionary.Where(pair => pair.Key > 1).Select(k => k.Key).ToList();
然后将它们从列表中删除。
// remove from the main collection
foreach (var key in removeList)
{
myDictionary.Remove(key);
}