Queue.ToArray Method in C#


The Queue.ToArray() method in C# copies the Queue elements to a new array.

Syntax

The syntax is as follows −

public virtual object[] ToArray ();

Example

Let us now see an example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Queue<int> queue = new Queue<int>();
      queue.Enqueue(1);
      queue.Enqueue(2);
      queue.Enqueue(3);
      queue.Enqueue(4);
      queue.Enqueue(5);
      Console.WriteLine("Queue...");
      foreach(int i in queue){
         Console.WriteLine(i);
      }
      int[] intArr = queue.ToArray();
      Console.WriteLine("Convert Queue to Array...");
      foreach(int i in intArr){
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

ueue...
1
2
3
4
5
Convert Queue to Array...
1
2
3
4
5

Example

Let us now see another example −

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");
      Console.WriteLine("Array...");
      foreach(string i in queue){
         Console.WriteLine(i);
      }
      string[] strArr = queue.ToArray();
      Console.WriteLine("Convert Queue to Array...");
      foreach(string i in strArr){
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

Array...
A
B
C
D
E
F
Convert Queue to Array...
A
B
C
D
E
F
raja
Published on 03-Dec-2019 07:39:20
Advertisements