Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a Queue is empty?

Tags:

c#

is-empty

queue

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?

like image 383
MoShe Avatar asked Nov 01 '11 15:11

MoShe


People also ask

How do you test for an empty queue in C?

isEmpty/isFull- checks if the queue is empty or full.

How can you check the conditions when queue is full or empty?

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.


3 Answers

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...
}
like image 82
Jon Skeet Avatar answered Oct 22 '22 08:10

Jon Skeet


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
    }
like image 37
GregoryBrad Avatar answered Oct 22 '22 07:10

GregoryBrad


Assuming you meant System.Collections.Generic.Queue<T>

if(yourQueue.Count != 0) { /* Whatever */ }

should do the trick.

like image 9
vcsjones Avatar answered Oct 22 '22 06:10

vcsjones