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

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

    Reverse iteration should be the first thing to come to mind when you want to remove elements from a Collection while iterating over it.

    Luckily, there is a more elegant solution than writing a for loop which involves needless typing and can be error prone.

    ICollection test = new List(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
    
    foreach (int myInt in test.Reverse())
    {
        if (myInt % 2 == 0)
        {
            test.Remove(myInt);
        }
    }
    

提交回复
热议问题