The problem when you want to remove items from a list you're iterating over is that the enumerator loses track of where you are in the list.
It's a bit like sawing a branch on which you are sitting. You shoudn't do it because it will have unecptected behaviour.
Now, how can this be solved?
Quite easily, you need make a copy of your list, iterate over your copy, and remove the items from your original list.
Sounds like a lot of code, but the only thing that you need to do is add ToList() in your foreach statement.
Example:
// This will throw an error, because you're modifying the original collection in your foreach statement.
var persons = new List<Persons>();
persons.Add(new Person());
persons.Add(new Person());
persons.Add(new Person());
foreach (var p in persons) {
persons.remove(p);
}
// This will NOT throw an error, because you're looping over a copy of the pesons list and remove items from the original one.
persons.Add(new Person());
persons.Add(new Person());
persons.Add(new Person());
foreach (var p in persons.ToList()) {
persons.remove(p);
}
Now, why does this work?
It's because ToList() creates a copy of your list in memory. So basiclly, your iterating over a copy of the collection right now.