简体   繁体   English

如何从字典中删除所有元素?

[英]How to remove all elements from a dictionary?

I use the following code to remove all elements from a dictionary: 我使用以下代码从字典中删除所有元素:

internal static void RemoveAllSourceFiles()
        {
            foreach (byte key in taggings.Keys)
            {
                taggings.Remove(key);
            }
        }

But unfortunately this isn't working because an InvalidOperationException is thrown. 但不幸的是,这不起作用,因为抛出了InvalidOperationException I know this is because the collection is modified while iterating over it, but how can I change that? 我知道这是因为在迭代它时修改了集合,但我怎么能改变它呢?

A much simpler (and much more efficient) approach: 一种更简单(也更有效)的方法:

taggings.Clear();

and yes, the error is because changing the data deliberately breaks iterators. 是的,错误是因为故意更改数据会破坏迭代器。

Try using the Clear method instead. 请尝试使用Clear方法。

internal static void RemoveAllSourceFiles()
        {
           taggings.Clear();
        }

Update: And as Marc pointed out, you cannot continue iterating over a collection while you modify it because the iterator is irrecoverably invalidated. 更新:正如Marc指出的那样,在修改它时,你不能继续迭代一个集合,因为迭代器无法恢复。 Please read the answer to this SO question for details. 有关详细信息,请阅读此SO问题的答案。

Why does enumerating through a collection throw an exception but looping through its items does not 为什么枚举通过集合抛出异常但循环遍历其项目却没有

To do what you want to do you are going to need to iterate through the keys in reverse, that way you do not modify the array in the order it is trying to return to you. 要执行您想要执行的操作,您将需要反向遍历键,这样您就不会按照尝试返回给您的顺序修改数组。

Either that or use .Clear() 无论是那个还是使用.Clear()

As said, the .NET default enumerator doesn't support collection changes while enumerating. 如上所述,.NET默认枚举器在枚举时不支持集合更改。 In your case use Clear. 在您的情况下使用清除。

If you want better control over deletion, use linq: 如果您想更好地控制删除,请使用linq:

var deletionList = (from tag in taggings where <where clause> select tag.Key).ToArray();
foreach(var key in deletionList)
{
   taggings.Remove(key);
}

The ToArray() extension method will enumerate the LINQ query, and instantiate an array storing the results. ToArray()扩展方法将枚举LINQ查询,并实例化存储结果的数组。 This array can be safely enumerated later to delete the contained items in the source dictionary. 可以在以后安全地枚举此数组,以删除源字典中包含的项。

I know this is an old question, but for any who's looking for an answer, here some options: 我知道这是一个老问题,但对于任何正在寻找答案的人来说,这里有一些选择:

  • To list() and then use the .remove property . list()然后使用.remove property
  • Make it null/nothing and reinit it? 让它为null / nothing并重新启动它?
  • Forloop in stead of foreach ? Forloop代替foreach
while Dict.Count()
  clDictObject oBj = Dict.Keys.ElementAt(dict.Count -1);
  Dict.Remove(oBj)
end while

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM