Author : MD TAREQ HASSAN | Updated : 2021/03/22

Creating Queue

// creating queue
var items = new Queue<string>();

//  enqueueing
items.Enqueue("foo");
items.Enqueue("bar");
items.Enqueue("bax");

// creating from array
var items = new Queue<string>(new string[] { "foo", "bar", "bax" });  
foreach(var item in items){
	Console.WriteLine(item);
}

Links

Queue Methods

// count
var count = items.Count;   // 3

// peek
var foo = items.Peek();      // items.Count => 3

// dequeue
var foo = items.Dequeue();     //  items.Count => 2

// Contains
var hasBax = items.Contains("bax");   // true

// remove all items
items.Clear();      //  items.Count => 0

Char Array to Queue

var chars = new char[] { 'a', 'x', 'b', 'y', 'c', 'z'};
var charQueue = new Queue<char>(chars);
foreach(var ch in charQueue){  // prints chars in order
	Console.WriteLine(ch);
}

Queue to Char Array

var charQueue = new Queue<char>( new char[] { 'a', 'x', 'b', 'y', 'c', 'z'});
var chars = charQueue.ToArray();  // if you print chars, compiler will automatically call chars.ToString() and therefore will be printed as "axbycz", but actually char[]
foreach(var ch in chars){
	Console.WriteLine(ch);
}

// CopyTo()
var charQueue = new Queue<char>( new char[] { 'a', 'x', 'b', 'y', 'c', 'z'} );
var chars = new char[charQueue.Count];
charQueue.CopyTo(chars, arrayIndex: 0);
foreach(var ch in chars){
	Console.WriteLine(ch);
}

String to Queue

var str = "ax by cz";
var wordQueue = new Queue<string>(str.Split(" "));
foreach(var word in wordQueue){
	Console.WriteLine(word);
}

Queue to String

var wordQueue = new Queue<string>(new string[]{ "ax", "by", "cz" }) ;
var str = String.Join(" ",  wordQueue);
Console.WriteLine(str);

Array to Queue

var intArray = new int[] { 1, 3, 5, 7 };
var intQueue = new Queue<int>(intArray) ;
foreach(var item in intQueue){
	Console.WriteLine(item);
}

Queue to Array

var intQueue = new Queue<int>(new int[] { 1, 3, 5, 7 }) ;
var intArray = intQueue.ToArray();
foreach(var item in intArray){
	Console.WriteLine(item);
}

List to Queue

var list = new List<int>() { 1, 3, 5, 7 };
var intQueue = new Queue<int>(list) ;
foreach(var item in intQueue){
	Console.WriteLine(item);
}

Queue to List

var intQueue = new Queue<int>(new List<int>() { 1, 3, 5, 7 }) ;
var list = new List<int>(intQueue);
foreach(var item in list){
	Console.WriteLine(item);
}

// LINQ
var intQueue = new Queue<int>(new List<int>() { 1, 3, 5, 7 }) ;
var list = intQueue.ToList();
foreach(var item in list){
	Console.WriteLine(item);
}