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?

+3


source to share


4 answers


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.

+1


source


It is true, you repeat yourself on the same list. You need to create a temporary list and add items to this topic list in a loop. After the foreach completes, you need to use the AddRange method:



reminds.AddRange(tempList);

      

+2


source


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.

+2


source


No, you cannot insert an element while iterating through it. Your results will be incorrect. You will need to create a temporary list and execute AddRange () after.

0


source







All Articles