How to modify or delete items from an enumerable collection while iterating through it in C#

Iterating Backwards through the List sounds like a better approach, because if you remove an element and other elements “fall into the gap”, that does not matter because you have already looked at those. Also, you do not have to worry about your counter variable becoming larger than the .Count.

        List<int> test = new List<int>();
        test.Add(1);
        test.Add(2);
        test.Add(3);
        test.Add(4);
        test.Add(5);
        test.Add(6);
        test.Add(7);
        test.Add(8);
        for (int i = test.Count-1; i > -1; i--)
        {
            if(someCondition){
                test.RemoveAt(i);
            }
        }

Leave a Comment