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.
bullets.RemoveAll(bullet => bullet.Offscreen());
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 the RemoveAll
method found in non-Silverlight frameworks, the built-in one will be used when available, and this one used seamlessly for silverlight builds.
public static class ListExtensions
{
public static int RemoveAll<T>(this List<T> list, Predicate<T> match)
{
if (list == null)
throw new NullReferenceException();
if (match == null)
throw new ArgumentNullException("match");
int i = 0;
int j = 0;
for (i = 0; i < list.Count; i++)
{
if (!match(list[i]))
{
if (i != j)
list[j] = list[i];
j++;
}
}
int removed = i - j;
if (removed > 0)
list.RemoveRange(list.Count - removed, removed);
return removed;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With