foreach Collection was modified; enumeration operation may not execute

15,343

You are not allowed to modify a loop's list inside the loop. So create a new list of that same thing:

var predcostssubjForLoop = predcostssubj.ToList();

and then do a

foreach (PredCost pc in predcostssubjForLoop )

but continue to modify predcostssubj inside the loop

As a side note, I suggest you check out the book Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin

Share:
15,343
user3047041
Author by

user3047041

Updated on June 05, 2022

Comments

  • user3047041
    user3047041 over 1 year

    I am trying to run a test generation and passing some of the test outputs to a foreach loop, but every other time I try to run the method it stops and the in in the foreach loop it gives an exception

    System.InvalidOperationException occurred in mscorlib.dll

    and then the Exception is caught in the try catch and gives the error

    Collection was modified; enumeration operation may not execute

    I'm not entirely sure why this error is being produced!