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?
isEmpty/isFull- checks if the queue is empty or full.
Now, we can check for the conditions. When Queue Full : ( REAR+1)%n = (4+1)%5 = 0 FRONT is also 0. Hence ( REAR + 1 ) %n is equal to FRONT. When Queue Empty : REAR was equal to FRONT when empty ( because in the starting before filling the queue FRONT = REAR = 0 ) Hence Option A is correct.
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
}
Assuming you meant System.Collections.Generic.Queue<T>
if(yourQueue.Count != 0) { /* Whatever */ }
should do the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With