Get the object at the beginning of the Queue – Peek Operation in C#

CsharpServer Side ProgrammingProgramming

To get the object at the beginning of the Queue, the code is as follows −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("A");
      queue.Enqueue("B");
      queue.Enqueue("C");
      queue.Enqueue("D");
      queue.Enqueue("E");
      queue.Enqueue("F");
      queue.Enqueue("G");
      Console.WriteLine("Count of elements = "+queue.Count);
      Console.WriteLine("Element at the beginning of queue = " + queue.Peek());
   }
}

Output

This will produce the following output −

Count of elements = 7
Element at the beginning of queue = A

Example

Let us see another example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("A");
      queue.Enqueue("B");
      queue.Enqueue("C");
      queue.Enqueue("D");
      queue.Enqueue("E");
      queue.Enqueue("F");
      queue.Enqueue("G");
      Console.WriteLine("Count of elements = "+queue.Count);
      Console.WriteLine("Element at the beginning of queue = " + queue.Peek());
      queue.Enqueue("H");
      queue.Enqueue("I");
      queue.Enqueue("J");
      Console.WriteLine("Count of elements = "+queue.Count);
      Console.WriteLine("Element at the beginning of queue = " + queue.Peek());
   }
}

Output

This will produce the following output −

Count of elements = 7
Element at the beginning of queue = A
Count of elements = 10
Element at the beginning of queue = A
raja
Published on 05-Dec-2019 11:01:58
Advertisements