C# Advanced

C# Queue

The objective of this article is to familiarize you with the generic C# Queue, which is implemented via Queue 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
C# Queue Animation

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.

C# Queue Class Common Properties and Methods

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
C# Queue Constructor Initialization 1

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
C# Queue Constructor Initialization 2

Run Demo

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");
C# Queue Enqueue Method 2

Run Demo

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");
C# Queue Dequeue Method 3

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();
C# Queue Dequeue Method 3.1

Run Demo

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();

Run Demo


C# Queue Methods

Queue<string> planets = new Queue<string>();
planets.Enqueue("Mercury");
planets.Enqueue("Venus");
planets.Enqueue("Earth");
C# Queue Enqueue Method 3

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();
C# Queue Peek Method 4

Run Demo

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
C# Queue Contains Method 5

Run Demo

Output

True


ToArray()

Copies the Queue<T> elements to a new array.

Signature: T[] ToArray()

var PlanetsArray = planets.ToArray();
C# Queue ToArray Method 6

Run Demo

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

Run Demo


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);

Run Demo

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());

Run Demo

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);
C# Queue Constructor Initialization grades 1
//Enqueue() to add item at the end
grades.Enqueue('D');
grades.Enqueue('E');
C# Queue Enqueue Method grades 2
foreach (char grade in grades)
    Console.WriteLine(grade);

//Peek() to get a single item from the beginning
Console.WriteLine(grades.Peek()); // Prints A
C# Queue Peek Method grades 3
//Contains()
Console.WriteLine(grades.Contains('B')); // Prints True
C# Queue Contains Method grades 4
//Count to get the total number of items
Console.WriteLine(grades.Count); // Prints 5
C# Queue Count Property grades 5
//Dequeue() to remove a single item from the beginning
Console.WriteLine(grades.Dequeue()); // Prints A
Console.WriteLine(grades.Count); // Prints 4
C# Queue Dequeue Method grades 6
//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

Run Demo

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);

Run Demo

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

Run Demo


C# Reference | Microsoft Docs