You cannot directly modify the collection inside foreach
- You cannot modify a collection inside a foreach method.
- Below is one of the way to modify the collection.
- Use select to modify and give us a new list.
- Assign back to the existing collection.
var numCollection = new List() { 6, 12, 24 };
try
{
for (int i = 4; i < 12;)
{
var list = numCollection.Select(a => a - i);
numCollection = list.ToList();
i = i + 4;
}
}
catch (Exception)
{
}