I want to do a breadth first search of a tree using a Queue
var q = new Queue<T>(); q.Enqueue(Root); foreach(T root in q) { foreach(T t in root.Children) q.Enqueue(t); }
However I get a ‘Collection was modified after the enumerator was instantiated.’ Exception.
Is there a C# type that I can do this with?
Edit: a little reading make me thing I might be doing this totally wrong.
Is there a way to use a foreach to dequeue from a Queue?
this works but is ugly (OMHO)
var q = new Queue<T>(); q.Enqueue(Root); while(q.Count > 0) { T root = q.Dequeue(); foreach(T t in root.Children) q.Enqueue(t); }
You can’t enumerate over an IEnumerable and change the same IEnumerable at the same time. I don’t think there is a C# Collection that will allow this.