How to remove elements from a generic list while iterating over it?

前端 未结 27 2816
忘了有多久
忘了有多久 2020-11-21 22:48

I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from

27条回答
  •  没有蜡笔的小新
    2020-11-21 23:20

    You can't use foreach, but you could iterate forwards and manage your loop index variable when you remove an item, like so:

    for (int i = 0; i < elements.Count; i++)
    {
        if ()
        {
            // Decrement the loop counter to iterate this index again, since later elements will get moved down during the remove operation.
            elements.RemoveAt(i--);
        }
    }
    

    Note that in general all of these techniques rely on the behaviour of the collection being iterated. The technique shown here will work with the standard List(T). (It is quite possible to write your own collection class and iterator that does allow item removal during a foreach loop.)

提交回复
热议问题