I have the following loop:
List<Reminders> reminds = new List<Reminders>();
//...
foreach (Reminders remind in reminds)
{
//....
reminds.Insert(id, new Reminders() { Title = remind.Title, Content = remind.Content, Checked = true });
}
However, an error occurs in the foreach
loop.
foreach (Reminders remind in reminds)
If I remove the reminds.Insert
statement, the error no longer occurs. I'm trying to update some entires inside of the foreach
loop. What's causing the error?
Change your Code to this:
List<Reminders> reminds = new List<Reminders>();
...
foreach (Reminders remind in reminds.ToList())
{
....
reminds.Insert(id, new Reminders() { Title = remind.Title, Content = remind.Content, Checked = true });
}
Please note the .ToList() behind reminds.
Explanation: You are not allowed to modify a collection while it is enumerated in an foreach. The .ToList() will create another temporary collection which will be constrant during the foreach loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With