Inserting a c # list into foreach
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, foreach
an error occurs in the loop .
foreach (Reminders remind in reminds)
If I remove the statement reminds.Insert
, the error no longer occurs. I am trying to update some elements inside a loop foreach
. What is causing the error?
source to share
If you want to update some records, then you will not add new ones, just set the property Checked
to true
for each record:
List<Reminders> reminds = new List<Reminders>();
...
foreach (Reminders remind in reminds)
{
....
remind.Checked = true;
}
You shouldn't change the list you are running.
source to share
Change your code to:
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 });
}
Note that the .ToList () header resembles.
Explanation: You are not allowed to modify a collection while it is enumerated in foreach..ToList () will create a temporary collection of another one that will be created during the foreach loop.
source to share