如何在C#中迭代集合时添加或删除对象 [英] How add or remove object while iterating Collection in C#
本文介绍了如何在C#中迭代集合时添加或删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在尝试通过Collection迭代时删除对象。但我得到例外。我该如何实现呢?
这是我的代码:
I am trying to remove object while I am iterating through Collection. But I am getting exception. How can I achieve this? Here is my code :
foreach (var gem in gems)
{
gem.Value.Update(gameTime);
if (gem.Value.BoundingCircle.Intersects(Player.BoundingRectangle))
{
gems.Remove(gem.Key); // I can't do this here, then How can I do?
OnGemCollected(gem.Value, Player);
}
}
推荐答案
foreach
要从集合中移除项目,而迭代它使用一个for循环从它的结尾到开始。 / p>
To remove items from a collection while iterating over it use a for loop from the end to the start of it.
for(int i = gems.Count - 1; i >=0 ; i--)
{
gems[i].Value.Update(gameTime);
if (gems[i].Value.BoundingCircle.Intersects(Player.BoundingRectangle))
{
Gem gem = gems[i];
gems.RemoveAt(i); // Assuming it's a List<Gem>
OnGemCollected(gem.Value, Player);
}
}
如果是字典< string,Gem>
例如,你可以这样迭代:
If it's a dictionary<string, Gem>
for example, you could iterate like this:
foreach(string s in gems.Keys.ToList())
{
if(gems[s].BoundingCircle.Intersects(Player.BoundingRectangle))
{
gems.Remove(s);
}
}
这篇关于如何在C#中迭代集合时添加或删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文