C Sharp Queue

C# Queue<T>

To Enqueue and Dequeue elements using the concept of Queue where elements are arranged in the First In First Out (FIFO) order, the C# Queue<T> class is used which is found in the System.Collections.Generic namespace. Duplicate elements can also be stored in a C# Queue<T> class.

Example:

using System;  
using System.Collections.Generic;  
 
public class Example  
{  
    public static void Main(string[] args)  
    {  
        Queue countries = new Queue();  
        countries.Enqueue("India");  
        countries.Enqueue("Australia");  
        countries.Enqueue("Canada");  
        countries.Enqueue("Japan");  
        countries.Enqueue("Mexico");  
 
        foreach (string country in countries)  
        {  
            Console.WriteLine(country);  
        }  
 
        Console.WriteLine("Peek element: "+ countries.Peek());  
        Console.WriteLine("Dequeue: "+ countries.Dequeue());  
        Console.WriteLine("Peek element After Dequeue: " + countries.Peek());  
    }  
}

Output:

Explanation:

In the above example, we are using the generic Queue<T> class. Here, the Enqueue() method is used to store the elements, the Dequeue() method is used to remove the elements and the for-each loop is used to iterate the elements.