C# Queue
Queue
Think of a line of people at a shop. The first person in the line is served first, and new people join at the end of the line.
A Queue in C# works the same way. This is called first in, first out (FIFO).
A printer works like this too. When you send many documents to a printer, it prints them in the order they arrived.
A queue is the opposite of a Stack, where the last item in is the first item out.
Like List, Queue is in the System.Collections.Generic namespace:
Example
// Include the namespace that holds Queue
using System.Collections.Generic;
Enqueue and Peek
Enqueue() adds an item to the end of the queue. Peek() returns the first item, without removing it:
Example
Queue<string> customers = new Queue<string>();
customers.Enqueue("Liam");
customers.Enqueue("Jenny");
customers.Enqueue("Angie");
Console.WriteLine(customers.Peek()); // Liam
Liam came first, so he is first in the queue.
Dequeue Items
Dequeue() removes the first item and returns it. Count tells you how many items are left:
Example
Queue<string> customers = new Queue<string>();
customers.Enqueue("Liam");
customers.Enqueue("Jenny");
customers.Enqueue("Angie");
Console.WriteLine(customers.Dequeue()); // Liam
Console.WriteLine(customers.Peek()); // Jenny
Console.WriteLine(customers.Count); // 2
Loop Through a Queue
A foreach loop goes through the queue from the first item to the last. It does not remove any items:
Example
Queue<string> customers = new Queue<string>();
customers.Enqueue("Liam");
customers.Enqueue("Jenny");
customers.Enqueue("Angie");
foreach (string customer in customers)
{
Console.WriteLine(customer);
}
Example: Print Jobs
This program puts three documents in a printer queue. Then it prints them one by one, until the queue is empty:
Example
Queue<string> printJobs = new Queue<string>();
printJobs.Enqueue("report.pdf");
printJobs.Enqueue("photo.jpg");
printJobs.Enqueue("letter.docx");
while (printJobs.Count > 0)
{
Console.WriteLine("Printing " + printJobs.Dequeue());
}
The documents are printed in the same order as they were added. Each Dequeue() removes one document, and the loop stops when Count is 0.