在C#中,如何检查队列是否为空?
我想遍历Queue的元素,我需要知道何时停止。我该怎么做?
我建议使用Any()方法,因为这不会对整个队列进行计数,因此在性能方面会更好。
Queue<string> queue = new Queue<string>();
// It's fine to use foreach...
foreach (string x in queue)
{
// We just won't get in here...
}
假设您的意思是Queue myQueue = new Queue();
if(myQueue.Any()){
//queue not empty
}
System.Collections.Generic.Queue<T>
应该做到这一点。
if(yourQueue.Count != 0) { /* Whatever */ }
有一个扩展方法.Count(),因为Queue实现了IEnumerable,所以它是可用的。
您也可以执行_queue.Any()来查看其中是否包含任何元素。
您可以检查其Count属性是否等于0。
YourQueue.GetEnumerator()。MoveNext()== true