In C#, how can I check if a Queue is empty?
I want to iterate through the Queue's elements, and I need to know when to stop. How can I accomplish this?
In C#, how can I check if a Queue is empty?
I want to iterate through the Queue's elements, and I need to know when to stop. How can I accomplish this?
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...
}
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.
Queue myQueue = new Queue();
if(myQueue.Any()){
//queue not empty
}
myQueue.Count
will not do a count over the entire queue. The size is stored in a private variable in the Queue class which the Count property just returns see Queue<T>.Count Property. The Count you mean is Count() in the linq namespace. Enumerable.Count –
Eliezer Queue.Any()
is available for use. –
Greave Assuming you meant System.Collections.Generic.Queue<T>
if(yourQueue.Count != 0) { /* Whatever */ }
should do the trick.
Queue test = new Queue();
if(test.Count > 0){
//queue not empty
}
There is an extension method .Count() that is available because Queue implements IEnumerable.
You can also do _queue.Any() to see if there are any elements in it.
TryPeek()
will let you check whether Queue has an element or not.
Queue q = new Queue();
if (!q.TryPeek(out object i)) {
/* Queue is empty */
....
}
© 2022 - 2025 — McMap. All rights reserved.