MoShe
MoShe

Reputation: 6427

How can I check if a Queue is empty?

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?

Upvotes: 47

Views: 107639

Answers (8)

soccer7
soccer7

Reputation: 4005

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 */
    ....
}

Upvotes: 0

Jevgenij
Jevgenij

Reputation: 11

YourQueue.GetEnumerator().MoveNext() == true

Upvotes: 0

GregoryBrad
GregoryBrad

Reputation: 1175

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
    }

Upvotes: 29

LMW-HH
LMW-HH

Reputation: 1193

    Queue test = new Queue();
    if(test.Count > 0){
      //queue not empty
    }

Upvotes: 3

Joe
Joe

Reputation: 42627

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.

Upvotes: 2

muddybruin
muddybruin

Reputation: 845

You can check if its Count property equals 0.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500825

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...
}

Upvotes: 61

vcsjones
vcsjones

Reputation: 141638

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

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

should do the trick.

Upvotes: 10

Related Questions