开发者

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

开发者 https://www.devze.com 2022-12-27 18:56 出处:网络
Here is what I am trying to do: private readonly IDictionary<float, ICollection<IGameObjectController>> layers;

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);
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号