Things to note when deleting list elements in a loop

less than 1 minute read

If you’re looping through a list and want to remove elements from that list, loop around ** in reverse order **.

NG


        for (int i = 0; i < enemyList.Count; i++) {
            if (!enemyList[i].IsAlive) {
                enemyList.RemoveAt(i);
            }
        }

OK


        for (int i = enemyList.Count - 1; i >= 0; i--) {
            if (!enemyList[i].IsAlive) {
                enemyList.RemoveAt(i);
            }
        }

Why do we have to reverse the order? The figure below shows. On the NG side, when the element C is deleted, the element behind it is packed to the front, causing the problem that the element D is not processed correctly.

figure.png

By the way, RemoveAll is useful when you want to remove an element of a list but you don’t need to do it ** in a loop **.

python


        enemyList.RemoveAll(enemy => !enemy.IsAlive);

Reference link

-How to delete a list element while enumerating a list?