本文介绍了在枚举时插入队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用队列对树进行广泛的首次搜索
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.
有没有C#类型,我可以这样做?
Is there a C# type that I can do this with?
编辑:一点点阅读让我的东西,我可能会这样做完全错误。
a little reading make me thing I might be doing this totally wrong.
有没有办法使用foreach从队列中排队?
Is there a way to use a foreach to dequeue from a Queue?
这样做是丑的(OMHO)
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);
}
推荐答案
你不能枚举过一个IEnumerable并同时更改相同的IEnumerable。我不认为有一个C#集合将允许这个。
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.
这篇关于在枚举时插入队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!