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.
It is better to either create a list that will contain items to remove, then remove items from the list:
Try this:
Attempting to remove it within a foreach loop will throw an exception. You need to iterate through it backwards with a for loop.
I've come across this problem before and blogged about it here.
Short version is that you can create an extension method called RemoveIf:
And then just call it with your delegate each time you need it:
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:
Or you can select the ones you do want, instead of removing the ones you don't:
Or use the indexer to move backwards through the sequence:
Edit: To make this work as-is in silverlight, add the following extension method to your project.
Like
List<T>.RemoveAll
, this algorithm is O(N) where N is the length of the list as opposed to O(N*M) where M is the number of elements removed from the list. Since it's an extension method with the same prototype as theRemoveAll
method found in non-Silverlight frameworks, the built-in one will be used when available, and this one used seamlessly for silverlight builds.