can you tell me if after each time I call Count, the Queue go over all the Queue and count or the Queue have a property of int Count and each adding/removing it increase/decrease?
Anyway, Is there a better way to know if the Queue is empty?
See the MSDN docs (1st hit in Google for "queue.count property"):
Retrieving the value of this property is an O(1) operation.
The capacity of a
Queue<T>is the number of elements that theQueue<T>can store.Countis the number of elements that are actually in theQueue<T>.The capacity is always greater than or equal to
Count. IfCountexceeds the capacity while adding elements, the capacity is increased by automatically reallocating the internal array before copying the old elements and adding the new elements.Retrieving the value of this property is an O(1) operation.
Taken from the source Queue<T>.Count Property on MSDN
A better way to know if a Queue is empty is to use IEnumerable's Any method.
This way you won't need to iterate over the whole collection simple to know if there's at least one item in the collection when using a Count method.
if(myQueue.Any())
{
// Do something.
}
In the case where Count is a property there will be a minor performance gain using Count vs Any however I think that the intent of the programmer is better preserved through Any in many cases, especially when the purpose of the check is to see if any items exist or not.
Any() is always going to be at least a tad slower.Any() is faster is only true in comparison to Enumerable.Count(), and only if the class doesn't implement a fast ICollection<T>.Count. One could argue that Any() reads better than Count>0, but that's only a stylistic choice.Any is a tad slower, you are correct.Count of the queue would iterate through all elements.Queue<T>.Count property, not the Enumerable.Count() method. Enumerable.Any will force the Queue<T> to enumerate the first element, if it exists. If the OP just wanted to know if there were any elements in the queue, queue.Count > 0 (or queue.Count == ) is faster than Enumerable.Any