gpt4 book ai didi

c# - while循环中的字典并删除字典中的项目

转载 作者:行者123 更新时间:2023-11-30 19:10:41 24 4
gpt4 key购买 nike

我有一个字典,如果字典中的项目通过所有处理,我想删除它。

            var dictEnum = dictObj.GetEnumerator();
while (dictEnum.MoveNext())
{
Parallel.ForEach(dictObj, pOpt, (KVP, loopState) =>
{
processAndRemove(KVP.Key);
});
}

private void processAndRemove(string keyId)
{
try
{
<does stuff>
dictObj.Remove(keyId);
} catch(exception ex) {
...
<does not remove anything, wants to retry until it doesn't fail>
}
}

我希望循环继续处理字典中所有剩余的项目(未删除的)。

但是,我遇到了一个错误。当我运行此代码的更简单版本时,我收到一条消息:

Collection was modified; enumeration operation may not execute

有没有办法使用字典来做到这一点?

更新:

只是为了提供更多背景信息。这背后的想法是,如果 dictObj 中还有剩余的项目,循环将继续运行。因此,如果我从第 10 次和第 8 次通过开始,我想重新运行直到他们通过才通过的第 2 次。

最佳答案

正如 Jalayn 所说,您不能在枚举集合时从集合中删除它。您必须重写代码以将其添加到另一个集合,然后枚举该集合并从原始集合中删除项目。

类似于:

var toRemove = new Dictionary<int, string>() //whatever type it is

Parallel.ForEach(dictObj, pOpt, (KVP, loopState) =>
{
toRemove.Add(KVP);
});

foreach (var item in toRemove)
{
dictObject.Remove(item.Key);
}

关于c# - while循环中的字典并删除字典中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16309539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com