Can I safely add nodes to LinkedList container inside foreach statement? Is there any difference if I used while loop? Or it is never allowed and can cause some problems?
foreach(var node in myList)
{
if(condition)
myList.AddLast(new MyNode());
}
Will it always work?
You can’t modify a collection while you’re enumerating over it.
From the docs for
LinkedList<T>.GetEnumerator:In practice I believe it will always throw an
InvalidOperationException, despite the behaviour officially being undefined.EDIT: You asked in a comment whether a
whileloop would help… a while loop usingGetEnumerator/MoveNext/Currentwouldn’t, but this will:As far as I’m aware, that’s entirely safe and predictable. You can always ask a node for its next node. If you happen to be looking at the tail node and add another one, you’ll get the new tail node when you ask for “next”.
If that doesn’t help, please give us more details about what you’re trying to achieve.