How to create a queue from an existing collection in C#

The Queue<T> generic class in the System.Collections.Generic namespace provides the Queue<T>(IEnumerable<T>) constructor, which is used to create a new instance of Queue<T> with elements copied from the specified Collection of elements.

Syntax

public Queue (System.Collections.Generic.IEnumerable<T> collection);

This constructor takes an IEnumerable<T> as input, and copies the elements for the specified collection to create a new instance of Queue.

Things to note

  • This method throws an exception if the input collection is null.
  • This is an O(n) operation, where n is the number of elements in the specified collection.
  • The Queue<T> instance created with this constructor has elements in the same order as present in the IEnumerator<T> of the specified collection.

In this example, we first declare and initialize an array of strings with names of months and print the contents of the array.

Next, we create a new instance of Queue<string>; we pass the array of strings in the Queue constructor parameter.

 Queue<string> monthQueue = new Queue<string>(monthsArray);

We demonstrate how this constructor functions with an example of a List of strings as well.

using System;
using System.Collections.Generic;
class QueueConstructor
{
static void Main()
{
string[] monthsArray = {"January", "Feburary", "March", "April"};
Console.WriteLine("Array Elements: {0}", string.Join(",", monthsArray));
Queue<string> monthQueue = new Queue<string>(monthsArray);
Console.WriteLine("Enqueued all array Elements to the Queue \nQueue Items : {0}", string.Join(",", monthQueue.ToArray()));
List<string> animals = new List<string>{"dog","cat", "lion", "zebra"};
Console.WriteLine("List Elements: {0}", string.Join(",", animals.ToArray()));
Queue<string> animalQueue = new Queue<string>(animals);
Console.WriteLine("Enqueued all List Elements to the Queue \nQueue Items : {0}", string.Join(",", animalQueue.ToArray()));
}
}

Free Resources