如何迭代TDictionary和删除项目? [英] How to iterate a TDictionary and delete item?

查看:111
本文介绍了如何迭代TDictionary和删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TDictionary,并向其中添加了一些项目:

I have a TDictionary and add some items to it:

for index := 0 to 10 do
   dict.Add(IntToStr(index), index);

现在,我需要迭代容器并删除想要的物品:

Now, I need to iterate the container and remove items I wanted:

pairEnum := dict.GetEnumerator;
while pairEnum.MoveNext do
begin
  if pairEnum.Current.Value mod 2 = 0 then
     dict.Remove(pairEunm.Current.Key);
end;

我希望我现在在字典中只有奇数。但是我实际得到的是:

I expect I now only have odd number in the dictionary. But what I actually got are:

key=1 value=1
key=3 value=3
key=5 value=5
key=7 value=7
key=9 value=9
key=8 value=8 <-

为什么未从字典中删除 8?

Why the "8" wasn't removed from dictionary?

如果我添加更多项目。例如,

If I add more items. e.g.

for index := 0 to 12 do
   dict.Add(IntToStr(index), index);

然后,结果是正确的。这是为什么?如何正确迭代TDictionary并删除项目?谢谢。

Then, the result is correct. Why is that? How can I correctly iterate a TDictionary and remove items? Thanks.

推荐答案

在迭代可枚举的同时删除项是不安全的。您应该保留要删除的键的另一个列表,并在迭代完成后开始删除它们。

It is unsafe to remove items while iterating an enumerable. You should keep another list of the keys that you want to remove and start removing them once your iteration is completed.

这篇关于如何迭代TDictionary和删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆