How add or remove object while iterating Collection in C#

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

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

Leave a Comment