Dequeue whole queue

  • A+
Category:Languages

How can I dequeue all values in a Queue? In the following code when I try to do so loop stops in the middle. I don't understand.

Queue<int> integers = new Queue<int>();  for (int i = 0; i < 20; i++) {     integers.Enqueue(i); }  Console.WriteLine(integers.Count); // 20 Console.WriteLine();  for (int i = 0; i < integers.Count; i++) {     Console.WriteLine(integers.Dequeue()); // Stops at 10 }  Console.WriteLine(); Console.WriteLine(integers.Count); // 10 

 


Your integers.Count is decreasing every time you dequeue, so after ten iterations of your for loop, it will be at 10, so the loop will exit.
For your code to work, just save the length of your queue before the loop, like so:

var length = integers.Count; for (int i = 0; i < length; i++) {     Console.WriteLine(integers.Dequeue()); } 

edit: Above solution is with minimal changes to OP's code. As per suggestions in the comments (and other answers), a while loop is generally more recommended for this type of task:

while (integers.Count != 0) {     Console.WriteLine(integers.Dequeue()); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: