views:

108

answers:

3

Here is what I am trying to do:

        private readonly IDictionary<float, ICollection<IGameObjectController>> layers;

        foreach (ICollection<IGameObjectController> layerSet in layers.Values)
        {
            foreach (IGameObjectController controller in layerSet)
            {
                if (controller.Model.DefinedInVariant)
                {
                    layerSet.Remove(controller);
                }
            }
        }

Of course, this doesn't work, because it will cause a concurrent modification exception. (Is there an equivalent of Java's safe removal operation on some iterators?) How can I do this correctly, or with LINQ?

+3  A: 

Use ToList to create an indpendent list over which to enumerate items to be removed.

    foreach (ICollection<IGameObjectController> layerSet in layers.Values)
    {
        foreach (IGameObjectController controller in layerSet
                   .Where(c => c.Model.DefinedInVariant).ToList())
        {
            layerSet.Remove(controller);

        }
    }
AnthonyWJones
+4  A: 

First, you can create a separate list of objects that need to be removed, and then remove them in a separate loop.

Second, if your collection supports indexing, just do a for loop downwards from Count-1 to 0, and use RemoveAt.

Fyodor Soikin
+2  A: 
    private readonly IDictionary<float, ICollection<IGameObjectController>> layers;

    foreach (ICollection<IGameObjectController> layerSet in layers.Values)
    {
        List<IGameObjectController> toDelete = layerSet.Where(ls => ls.Model.DefinedInVariant).ToList();
        foreach (IGameObjectController controller in toDelete)
        {
           layerSet.Remove(controller);
        }
    }
Andrey