inserting into a queue while enumerating it

百般思念 提交于 2019-12-25 01:48:12

问题


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);
}

回答1:


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.




回答2:


The foreach construct won't work here.

You can solve the problem using a container that provides indexed access.

var l = new List<T>();
l.Add(Root);
int i = 0;
while(i < l.Count)
{
    T root = l[i];
    foreach(T t in root.Children)    
    {
        l.Add(t);
    }
    ++i;
}


// And because you really wanted a queue
var q = new Queue<T>(l);


来源:https://stackoverflow.com/questions/604478/inserting-into-a-queue-while-enumerating-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!