C# Queue

In C#, Queue<T> is a generic class that represents a first-in, first-out (FIFO) collection of objects. It is part of the System.Collections.Generic namespace. The <T> represents the type of elements that the queue will store.

Here’s an example of how to use the Queue<T> class in C#:

using System;
using System.Collections.Generic;

class Program
    static void Main()
        // Create a new queue of integers
        Queue<int> myQueue = new Queue<int>();

        // Enqueue elements to the queue

        // Dequeue elements from the queue
        int firstElement = myQueue.Dequeue();
        Console.WriteLine("Dequeued element: " + firstElement);

        // Peek at the first element in the queue without removing it
        int peekedElement = myQueue.Peek();
        Console.WriteLine("Peeked element: " + peekedElement);

        // Check the number of elements in the queue
        int count = myQueue.Count;
        Console.WriteLine("Number of elements in the queue: " + count);

        // Iterate over the queue elements
        foreach (int element in myQueue)
            Console.WriteLine("Queue element: " + element);

In this example, we create a queue called myQueue to store integers. We use the Enqueue method to add elements to the queue, and the Dequeue method to remove and retrieve the first element. The Peek method allows us to view the first element without removing it. The Count property gives us the number of elements in the queue. We can also use a foreach loop to iterate over the elements in the queue.

Remember to include the System.Collections.Generic namespace at the top of your file to use the Queue<T> class.