Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you remove an item from a List<> whilst iterating through it in C#

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.

like image 559
Chris Avatar asked Nov 27 '22 00:11

Chris


1 Answers

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;
    }
}
like image 198
Sam Harwell Avatar answered Dec 06 '22 05:12

Sam Harwell