Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
queue
peek
communitycreator

How to access the first element in a C# queue without its removal

Surabhi Sharma

The Queue<T> generic class in the System.Collections.Generic namespace provides the Peek() method, which is used to get the element at the beginning of the queue without its removal.

Syntax

public T Peek ();

This method returns the item at the beginning of the Queue<T>, but does not remove it.

Things to note

  • There is no change in the state of the state of the Queue after we call the Peek() method.

  • The time complexity of this method is O(1).

Getting the first element from beginning using Peek()

Example

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 FIFOFirst In, First Out data structure.

We then use the Peek() method to get the first element from the beginning of the queue.

We print all the elements of the queue again after the Peek() operation. We can observe in the output that the queue remains unchanged after the Peek() operation.

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 firstItem = months.Peek();        
        Console.WriteLine($"Found {firstItem} at beginning of the Queue using Peek()");
        Console.WriteLine("Queue Items After Peek() : {0}", string.Join(",", months.ToArray()));

       
    }
}

RELATED TAGS

c#
queue
peek
communitycreator
RELATED COURSES

View all Courses

Keep Exploring