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

前端 未结 27 2839
忘了有多久
忘了有多久 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:15

    The best way to remove items from a list while iterating over it is to use RemoveAll(). But the main concern written by people is that they have to do some complex things inside the loop and/or have complex compare cases.

    The solution is to still use RemoveAll() but use this notation:

    var list = new List(Enumerable.Range(1, 10));
    list.RemoveAll(item => 
    {
        // Do some complex operations here
        // Or even some operations on the items
        SomeFunction(item);
        // In the end return true if the item is to be removed. False otherwise
        return item > 5;
    });
    

提交回复
热议问题