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
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
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