Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List insert in foreach [closed]

Tags:

c#

foreach

insert

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?

like image 990
GoOx Avatar asked Dec 18 '14 16:12

GoOx


1 Answers

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.

like image 171
DrKoch Avatar answered Sep 20 '22 14:09

DrKoch