C# 在迭代字典时删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9892790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:06:11  来源:igfitidea点击:

Deleting while iterating over a dictionary

c#

提问by John Baum

Possible Duplicate:
Modifying .NET Dictionary while Enumerating through it

可能的重复:
在枚举时修改 .NET 字典

i have a dictionary object when i iterate over and do some operations. Based on a condition i should either delete or keep the keyvalue pair i am currently iterating over. What is the best way to delete a keyvaluepair from a dictionary while iterating over it? I tried to use a separate dictionary object to keep track of the elements to delete but im not sure how to then use it to delete from my main dictionary or if thats even the most efficient way to do it

当我迭代并执行一些操作时,我有一个字典对象。根据条件,我应该删除或保留我当前正在迭代的键值对。在迭代字典时从字典中删除键值对的最佳方法是什么?我尝试使用单独的字典对象来跟踪要删除的元素,但我不确定如何使用它从我的主字典中删除,或者这是否是最有效的方法

Thanks

谢谢

采纳答案by Rawling

Keep a list of the keys you wish to remove as you find them. Then, when you are done, iterate over this list, calling myDictionary.Remove(key)on each key you stored.

在您找到要删除的密钥时,请保留一份列表。然后,当你完成后,遍历这个列表,调用myDictionary.Remove(key)你存储的每个键。

回答by Euclides Mulémbwè

try using a separate dictionary and instead of marking the key value to delete insert da key values that you want to keep and at the and of the iteration do this: old_map = new_map.

尝试使用单独的字典,而不是标记键值以删除要保留的插入键值,并在迭代中执行此操作:old_map = new_map。