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?
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);
}
}
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.
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);
}
}
精彩评论