Queue.GetEnumerator() Method in C#


The Queue.GetEnumerator() method in C# is used to return an enumerator that iterates through the Queue.

Syntax

The syntax is as follows:

public virtual System.Collections.IEnumerator GetEnumerator ();

Example

Let us now see an example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Queue queue = new Queue();
      queue.Enqueue(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      queue.Enqueue(400);
      Console.WriteLine("Queue1...");
      IEnumerator demoEnum = queue.GetEnumerator();
      while (demoEnum.MoveNext()){
         Console.WriteLine(demoEnum.Current);
      }
      Queue queue2 = new Queue();
      queue2.Enqueue(100);
      queue2.Enqueue(150);
      queue2.Enqueue(300);
      queue2.Enqueue(400);
      Console.WriteLine("\nQueue2...");
      demoEnum = queue2.GetEnumerator();
      while (demoEnum.MoveNext()){
         Console.WriteLine(demoEnum.Current);
      }
      Console.WriteLine(queue.Equals(queue2));
   }
}

Output

This will produce the following output −

Queue1...
100
200
300
400
Queue2...
100
150
300
400
False

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Queue queue = new Queue();
      queue.Enqueue(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      queue.Enqueue(400);
      queue.Enqueue(500);
      queue.Enqueue(600);
      queue.Enqueue(700);
      queue.Enqueue(800);
      queue.Enqueue(900);
      queue.Enqueue(1000);
      Console.WriteLine("Queue...");
      IEnumerator demoEnum = queue.GetEnumerator();
      while (demoEnum.MoveNext()){
         Console.WriteLine(demoEnum.Current);
      }
   }
}

Output

This will produce the following output −

Queue...
100
200
300
400
500
600
700
800
900
1000
raja
Published on 03-Dec-2019 09:24:31
Advertisements