C#:如何使用LINQ从IDictionary <E,ICollection <T >>的集合中删除项目?

Nic*_*ner 3 c# linq generics collections

这是我想要做的:

        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);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

当然,这不起作用,因为它会导致并发修改异常.(在某些迭代器上是否有相当于Java的安全删除操作?)如何正确地执行此操作,或使用LINQ?

Ant*_*nes 5

使用ToList创建indpendent名单在其列举的项目被删除.

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

        }
    }
Run Code Online (Sandbox Code Playgroud)