In C#, how can I check if a Queue is empty?
在c#中,如何检查队列是否为空?
I want to iterate through the Queue's elements, and I need to know when to stop. How can I accomplish this?
我想遍历队列的元素,我需要知道何时停止。我怎样才能做到这一点呢?
6 个解决方案
#1
38
Assuming you mean Queue<T>
you could just use:
假设您的意思是队列
if (queue.Count != 0)
But why bother? Just iterate over it anyway, and if it's empty you'll never get into the body:
但何苦呢?不管怎样,只要重复一遍,如果它是空的,你就永远不会进入身体:
Queue<string> queue = new Queue<string>();
// It's fine to use foreach...
foreach (string x in queue)
{
// We just won't get in here...
}
#2
14
I would suggest using the Any() method, as this will not do a count on the entire queue, which will be better in terms of performance.
我建议使用Any()方法,因为这不会对整个队列进行计数,这在性能方面会更好。
Queue myQueue = new Queue();
if(myQueue.Any()){
//queue not empty
}
#3
7
Assuming you meant System.Collections.Generic.Queue<T>
假设你是System.Collections.Generic.Queue < T >
if(yourQueue.Count != 0) { /* Whatever */ }
should do the trick.
应该足够了。
#4
3
Queue test = new Queue();
if(test.Count > 0){
//queue not empty
}
#5
2
There is an extension method .Count() that is available because Queue implements IEnumerable.
有一个扩展方法. count()可用,因为队列实现了IEnumerable。
You can also do _queue.Any() to see if there are any elements in it.
您还可以执行_queue.Any()来查看其中是否有任何元素。
#6
1
You can check if its Count property equals 0.
您可以检查它的Count属性是否等于0。
#1
38
Assuming you mean Queue<T>
you could just use:
假设您的意思是队列
if (queue.Count != 0)
But why bother? Just iterate over it anyway, and if it's empty you'll never get into the body:
但何苦呢?不管怎样,只要重复一遍,如果它是空的,你就永远不会进入身体:
Queue<string> queue = new Queue<string>();
// It's fine to use foreach...
foreach (string x in queue)
{
// We just won't get in here...
}
#2
14
I would suggest using the Any() method, as this will not do a count on the entire queue, which will be better in terms of performance.
我建议使用Any()方法,因为这不会对整个队列进行计数,这在性能方面会更好。
Queue myQueue = new Queue();
if(myQueue.Any()){
//queue not empty
}
#3
7
Assuming you meant System.Collections.Generic.Queue<T>
假设你是System.Collections.Generic.Queue < T >
if(yourQueue.Count != 0) { /* Whatever */ }
should do the trick.
应该足够了。
#4
3
Queue test = new Queue();
if(test.Count > 0){
//queue not empty
}
#5
2
There is an extension method .Count() that is available because Queue implements IEnumerable.
有一个扩展方法. count()可用,因为队列实现了IEnumerable。
You can also do _queue.Any() to see if there are any elements in it.
您还可以执行_queue.Any()来查看其中是否有任何元素。
#6
1
You can check if its Count property equals 0.
您可以检查它的Count属性是否等于0。