The Queue<T>
generic class in the System.Collections.Generic
namespace provides the Dequeue()
method, which is used to remove and return an element from the beginning of the Queue<T>
.
public T Dequeue ();
Dequeue()
is called.In this example, we have created a queue of strings and enqueued a few month names to it. We then print all the items of the queue.
Notice that all the elements are inserted to the end of the queue as Queue
is a
We then use the Dequeue
method to remove the first two elements from the beginning of the queue.
We print all the elements of the queue again after the Dequeue()
operation. We can observe in the output that the top two elements, January
and February
, are removed from the beginning of the queue.
using System;using System.Collections.Generic;class QueueTest{static void Main(){Queue<string> months = new Queue<string>();months.Enqueue("January");months.Enqueue("February");months.Enqueue("March");months.Enqueue("April");months.Enqueue("May");months.Enqueue("June");Console.WriteLine("Enqueued elements to the Queue \nQueue Items : {0}", string.Join(",", months.ToArray()));string firtItem = months.Dequeue();string secondItem = months.Dequeue();Console.WriteLine($"Removed {firtItem} and {secondItem} from the Queue using Dequeue()");Console.WriteLine("Queue Items After Dequeue() : {0}", string.Join(",", months.ToArray()));}}