Can you remove an item from a List<> whilst iterating through it in C#
.net, c#, iteration, list, silverlight
Solution
Edit: to clarify, the question is regarding Silverlight, which apparently does not support RemoveAll on List`T. It is available in the full framework, CF, XNA versions 2.0+
You can write a lambda that expresses your removal criteria:
bullets.RemoveAll(bullet => bullet.Offscreen());
Or you can select the ones you do want, instead of removing the ones you don't:
bullets = bullets.Where(b => !b.OffScreen()).ToList();
Or use the indexer to move backwards through the sequence:
for(int i=bullets.Count-1;i>=0;i--)
{
if(bullets[i].OffScreen())
{
bullets.RemoveAt(i);
}
}
Problem
Can you remove an item from a List<> whilst iterating through it? Will this work, or is there a better way to do it? My code: ``` foreach (var bullet in bullets) { if (bullet.Offscreen()) { bullets.Remove(bullet); } } ``` -edit- Sorry guys, this is for a silverlight game. I didn't realise silverlight was different to the Compact Framework.