The objective of this article is to familiarize you with the generic C# Queue, which is implemented via Queue<T> collection class. You will learn how to declare, create, instantiate and use this type of collection, including code examples of the commonly used methods and properties of Queue<> class. Finally, different ways to iterate through all the items of the collection.
Table of Contents | |
What Is the Queue in C#?
C# Queue (pronounced cue) is a collection which represents a first-in, first-out (FIFO) mechanism, with methods where an item is added into the queue at the back with Enqueue method and is removed from the queue at the front with Dequeue method. In other words, lets you add or remove items at the head and tail. You cannot add items in the middle. Items are retrieved in the same order in which they were added.
C# Queue can be implemented with the Queue<T> class in the System.Collections.Generic namespace, where T specifies the type of items in the queue. You cannot use C# collection initializers with queues, because collection initializers are implemented using the Add method whereas queue uses Enqueue and Dequeue methods to add and retrieve items.
Properties and Methods of C# Queue Class
Mostly used methods of the Queue<T> class to perform different operations are listed below.
You can declare and initialize C# Queue as in the following code.
using Statement
To work with the C# Queue, you need to add the following namespace at the beginning your code:
using System.Collections.Generic;
How Do You Create a Queue in C#?
You can create C# Queue using either one or two statements.
Declare and Initialize C# Queue Using Two Statements
The T part of the declaration indicates that the class will work with a certain type.
Queue<T> queueName; // declaration
You use new keyword with default constructor to initialize an empty Queue.
queueName = new Queue<T>(); // initialization
You can also use a constructor to specify the capacity. As items are added to the queue, the capacity is automatically increased to hold more items. The capacity is doubled if required.
queueName = new Queue<T>(capacity);
The capacity can be decreased by calling TrimExcess method.
Declare and Initialize C# Queue on a Single Line
Queue<T> queueName = new Queue<T>(); // declaration & initialization
Use of var keyword to infer its type from the value that’s assigned to it.
var queueName = new Queue<T>();
Add Items to a C# Queue
string[] morePlanets = { "Mercury", "Venus", "Earth" }; // Array Queue<string> planets; // declaration
Constructor Initialization
You can initialize a new instance of the Queue<T> class that contains items copied from the morePlanets array.
Signature: Queue<T>(IEnumerable<T> collection)
planets = new Queue<string>(morePlanets); // initialization
OUTPUT
Mercury
Venus
Earth
Enqueue()
You can add a new item to the end of the Queue<T> using Enqueue method.
Signature: void Enqueue(T item)
planets = new Queue<string>(morePlanets); // initialization planets.Enqueue("Mars"); planets.Enqueue("Jupiter");
OUTPUT
Mercury
Venus
Earth
Mars <-
Jupiter <-
Remove Items from C# Queue
Queue<string> planets = new Queue<string>(); planets.Enqueue("Mercury"); planets.Enqueue("Venus"); planets.Enqueue("Earth");
Dequeue()
Dequeue method is used to remove and return the item at the front of the Queue<T>. Calling the Dequeue once more removes the next item from the queue. Invoking Dequeue method on empty queue will throw InvalidOperationException with the message ‘Queue empty.’. Always check count property before calling Dequeue method.
Signature: T Dequeue()
if (planets.Count > 0) planets.Dequeue();
OUTPUT
Venus
Earth
Clear()
The Clear method removes all the items from a Queue<T> and sets its Count property to zero.
Signature: void Clear()
planets.Clear();
C# Queue Methods
Queue<string> planets = new Queue<string>(); planets.Enqueue("Mercury"); planets.Enqueue("Venus"); planets.Enqueue("Earth");
Peek()
The Peek method returns the first item from the beginning of the Queue<T> but does not remove it. Calling the Peek once more retrieves the next item from the queue. If you use Peek method on empty queue, run time exception of type InvalidOperationException is thrown with the message ‘Queue empty.’
Signature: T Peek()
if (planets.Count > 0) planets.Peek();
OUTPUT
Mercury
Contains()
The Contains method checks and returns Boolean (True/False) value whether specified item exists in the Queue<T>.
Signature: bool Contains(T item)
planets.Contains("Venus"); // Returns True
OUTPUT
True
ToArray()
Copies the Queue<T> elements to a new array.
Signature: T[] ToArray()
var PlanetsArray = planets.ToArray();
OUTPUT
Mercury
Venus
Earth
C# Queue Property
Queue<string> planets = new Queue<string>(); planets.Enqueue("Mercury"); planets.Enqueue("Venus");
Count
To return total number of items in the queue, use the Count property.
planets.Count; // Returns 2
Processing of C# Queue with Loops
The first statement declares a queue named planets that contains 3 string values.
Queue<string> planets = new Queue<string>(); planets.Enqueue("Mercury"); planets.Enqueue("Venus"); planets.Enqueue("Earth");
Note: It doesn’t matter where you are modifying the collection. If a collection is modified while you are enumerating its members, you get exception.
foreach Loop
If you use C# foreach loop to iterate through a Queue<T> collection, you cannot use the iteration variable to modify the contents of the collection. Therefore, it’s safe to assume that using a foreach on a queue will not Dequeue any items. Any attempt to do that will result an exception of type InvalidOperationException with the message ‘Collection was modified; enumeration operation may not execute.’
Note: The foreach statement only allows reading from, not writing to, the collection.
foreach (var planet in planets) Console.WriteLine(planet); // iterate a Queue by converting it into an Array foreach (var planet in planets.ToArray()) Console.WriteLine(planet);
OUTPUT
Mercury
Venus
Earth
while Loop
Use of C# while loop to iterate through a Queue<T> collection.
while (planets.Count > 0) Console.WriteLine(planets.Dequeue());
// Namespace Required using System.Linq;
while (planets.Any()) Console.WriteLine(planets.Dequeue());
OUTPUT
Mercury
Venus
Earth
C# Queue Examples
This statement declares and initializes a queue of 3 characters. Once the queue is created, you can add items to the queue with the Enqueue method.
//Array char[] extraGrade = { 'A', 'B', 'C' }; Queue<char> grades = new Queue<char>(extraGrade);
//Enqueue() to add item at the end grades.Enqueue('D'); grades.Enqueue('E');
foreach (char grade in grades) Console.WriteLine(grade); //Peek() to get a single item from the beginning Console.WriteLine(grades.Peek()); // Prints A
//Contains() Console.WriteLine(grades.Contains('B')); // Prints True
//Count to get the total number of items Console.WriteLine(grades.Count); // Prints 5
//Dequeue() to remove a single item from the beginning Console.WriteLine(grades.Dequeue()); // Prints A Console.WriteLine(grades.Count); // Prints 4
//Using while loop to Dequeue() all the items 1 by 1 while (grades.Count > 0) Console.WriteLine(grades.Dequeue()); Console.WriteLine(grades.Count); // Prints 0 //Reset items grades = new Queue<char>(extraGrade); //Clear() to remove all the items grades.Clear(); Console.WriteLine(grades.Count); // Prints 0
Queue<string> Vegetables = new Queue<string>(); Vegetables.Enqueue("Carrot"); Vegetables.Enqueue("Cucumber"); Vegetables.Enqueue("Tomato"); Vegetables.Enqueue("Onion"); Vegetables.Enqueue("Green Pepper"); Queue<int> integerValues = new Queue<int>(3); integerValues.Enqueue(1); integerValues.Enqueue(2); integerValues.Enqueue(3); //Code that creates a queue that holds decimal values Queue<decimal> decimalValues = new Queue<decimal>(); decimalValues.Enqueue(13.2m); decimalValues.Enqueue(20.74m); decimalValues.Enqueue(8.34m);
var planets = new Queue<Planet>(); planets.Enqueue(new Planet() { Id = 1, Name = "Mercury" }); planets.Enqueue(new Planet() { Id = 2, Name = "Venus" }); planets.Enqueue(new Planet() { Id = 3, Name = "Earth" }); foreach (var planet in planets) Console.WriteLine($"{planet.Id}, {planet.Name}"); class Planet { public int Id { get; set; } public string Name { get; set; } }