C #: How to remove elements from the collection IDictionary <E, ICollection <T>> with LINQ?

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 does not work, because it will throw a parallel modification exception. (Is there an equivalent to the safe Java delete operation on some iterators?) How can I do this correctly or with LINQ?

+3
source share
3 answers

Use ToListto create an independent list for which you want to list items that you want to remove.

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

        }
    }
+5
source

First you can create a separate list of objects to be deleted, and then delete them in a separate cycle.

-, , for Count-1 0 RemoveAt.

+4
    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);
        }
    }
+3
source

Source: https://habr.com/ru/post/1742499/


All Articles