Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add or remove object while iterating Collection in C#

Tags:

c#

collections

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);
    }
}
like image 977
Hakoo Desai Avatar asked May 11 '13 12:05

Hakoo Desai


1 Answers

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);
   }
}
like image 155
graumanoz Avatar answered Sep 19 '22 18:09

graumanoz