C# - How to Peek Elements from Queue?

In this C# program, we will learn how to peek an element from Queue using collection framework? By IncludeHelp Last updated : March 28, 2023

Peek Elements from Queue

To peek elements from queue, we use Queue.Peek() method. This method return an elements without removing it from the queue.

Read More: Queue.Peek() Method

C# program to peek elements from Queue using collection

using System;
using System.Collections;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      Queue Q = new Queue(5);

      Q.Enqueue(10);
      Q.Enqueue(20);
      Q.Enqueue(30);
      Q.Enqueue(40);

      Console.WriteLine("Peeked item: " + Q.Peek());
      Console.WriteLine("Peeked item: " + Q.Peek());
      Console.WriteLine("Peeked item: " + Q.Peek());
      Console.WriteLine("Peeked item: " + Q.Peek());
    }
  }
}

Output

Peeked item: 10
Peeked item: 10
Peeked item: 10
Peeked item: 10

Explanation

In this program, we are inserting 4 items into queue, then getting items from queue without removing them, using Peek() method, so that we always got same item.

Note: In above program, to use 'Queue' class, we need to include System.Collection namespace.

C# Data Structure Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.