How add or remove object while iterating Collection in C#

后端 未结 5 1559
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 16:52

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          


        
5条回答
  •  天涯浪人
    2020-12-06 17:12

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

    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
          OnGemCollected(gem.Value, Player);
      }
     }
    

    If it's a dictionary for example, you could iterate like this:

    foreach(string s in gems.Keys.ToList())
    {
       if(gems[s].BoundingCircle.Intersects(Player.BoundingRectangle))
       {
         gems.Remove(s);
       }
    }
    

提交回复
热议问题