The collection looks like this:

public class myList : List<myClass> { } 

I need to repeat the cycle until it adds new elements:

 do { newObjectAdded = false; foreach (myClass obj in myList) { //... if (some_condition) { myList.Add(newObj); newObjectAdded = true;} //... } } while (newObjectAdded); 

After an element is added to the sheet, in the foreach (myClass obj in myList) line foreach (myClass obj in myList) I get an error - the collection has been changed, it is impossible to perform an enumeration operation.

You can replace foreach with a loop with an iterator, but this will make accessing objects rather cumbersome. There is also the option of replacing the list with LinkedList, but this is even worse, in this case.

Is there some more elegant way?

  • @InfernumDeus, I do not know the intricacies of Sharp, but performing foreach on a variable collection is not a very good approach. It is better to change to while (intermediate Store. Length> 0) {var x = intermediate Store ..pop (); } and update this intermediate storage, dropping items to the end. - etki

1 answer 1

I figured it out myself. It is enough to write:

 foreach (myClass obj in myList.ToArray()) { 
  • one
    Mark your answer as correct. - andreycha Nov.
  • In general, do not use this solution. You should think better and apply a separate temporary collection. - InfernumDeus 4:38 pm