The problem
An error was reported while performing a list removal operation with foreach
code
Foreach (var item in list) {if (judge condition) {list.remove (item); }}Copy the code
To solve
Method 1: Use the for loop
for (int i = 0; i < list.Count; I ++) {if (judge condition) {list.removeat (I); i--; }}Copy the code
Method 2: Use ToArray method
Foreach (var item in list.toarray ()) {if (judge condition) {list.remove (item); }}Copy the code