在 C# 中迭代​​ Collection 时如何添加或删除对象 [英] How add or remove object while iterating Collection in C#

查看:24
本文介绍了在 C# 中迭代​​ Collection 时如何添加或删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在遍历 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 旨在迭代一个集合而不修改它.

foreach is designed for iterating over a collection without modifing it.

要在迭代集合时从集合中删除项目,请使用从末尾到开头的 for 循环.

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);
  }
 }

如果它是一个 dictionary 例如,你可以像这样迭代:

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# 中迭代​​ Collection 时如何添加或删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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