You cannot modify the collection while looping through it in a
foreach
loop.
If you need to make modifications, you can use
for
loop instead, either from 0 to count-1 or vice versa (depending on the code).
From
foreach, in (C# Reference)[
^]:
The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.