C# Advance

C# Queue

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.

C# Queue<T> (generics)

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.

Queue T 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 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.

Common Properties and Methods of the Queue<T> Class

Mostly used methods of the Queue<T> class to perform different operations are listed below.

Queue-T

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;

Declaration and Instantiation 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.

Declaration and Instantiation Combined 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 Queue

string[] morePlanets = { "Mercury", "Venus", "Earth" }; // Array
Queue<string> planets; // declaration

Queue Constructor Initialization

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

Queue Constructor Initialization

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

Queue Enqueue Method

Run Demo

OUTPUT

Mercury
Venus
Earth
Mars <-
Jupiter <-

Remove Queue Items

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

Queue Dequeue Method

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

Queue Dequeue Method

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

Peek(), Contains(), and ToArray() Methods

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

Queue Enqueue Method

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

Queue Peek Method

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

Queue Contains Method

Run Demo

OUTPUT

True

ToArray()

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

Signature:T[] ToArray()

var PlanetsArray = planets.ToArray();

Queue ToArray Method

Run Demo

OUTPUT

Mercury
Venus
Earth

Count 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 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 foreach 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 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

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

Queue Constructor Initialization grades

//Enqueue() to add item at the end
grades.Enqueue('D');
grades.Enqueue('E');

Queue Enqueue Method grades

foreach (char grade in grades)
    Console.WriteLine(grade);

//Peek() to get a single item from the beginning
Console.WriteLine(grades.Peek()); // Prints A

Queue Peek Method grades

//Contains()
Console.WriteLine(grades.Contains('B')); // Prints True

Queue Contains Method grades

//Count to get the total number of items
Console.WriteLine(grades.Count); // Prints 5

Queue Count Property grades

//Dequeue() to remove a single item from the beginning
Console.WriteLine(grades.Dequeue()); // Prints A
Console.WriteLine(grades.Count); // Prints 4

Queue Dequeue Method grades

//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

Loops

C# Reference | Microsoft Docs