5

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?

Will Eddins
  • 13,628
  • 5
  • 51
  • 85
GoOx
  • 73
  • 1
  • 1
  • 9

4 Answers4

5

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.

DrKoch
  • 9,556
  • 2
  • 34
  • 43
  • While this could have memory and performance implications, if you have a reasonable idea of your list size then it's rather clever. Not sure if a junior programmer is going to see the nuance though. – Pale Ale Mar 25 '15 at 14:09
3

It's true, you are iterating in the same list. You need to create a temporary list, and add the elements in that temp list in the cycle. After, when the foreach finish, you need to use the method AddRange:

reminds.AddRange(tempList);
ocuenca
  • 38,548
  • 11
  • 89
  • 102
1

If you want to update some entries then you shoudn't add new ones just set the property Checked to true of each entry:

List<Reminders> reminds = new List<Reminders>();
...
foreach (Reminders remind in reminds)
{
    ....
    remind.Checked = true;
}

You must not modify the list that you are iterating.

t3chb0t
  • 16,340
  • 13
  • 78
  • 118
0

No, You can't insert into an item while iterating through it. Your results will be wrong. You will need to create a temporary list and do an AddRange() after.

Kevin
  • 1