Queue.CopyTo() Method in C#


The Queue.CopyTo() method in C# is used to copy the Queue elements to an existing one-dimensional Array, starting at the specified array index.

Syntax

The syntax is as follows −

public virtual void CopyTo (Array arr, int index);

Above, the parameter arr is the one-dimensional Array that is the destination of the elements copied from Queue. The index parameter is the zero-based index in array at which copying begins.

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(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      Console.Write("Count of elements = ");
      Console.WriteLine(queue.Count);
      Console.WriteLine("Queue...");
      foreach(int i in queue) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Does the queue has element 500? = "+queue.Contains(500));
      int[] intArr = new int[5];
      intArr[0] = 1;
      intArr[1] = 2;
      intArr[2] = 3;
      intArr[3] = 4;
      queue.CopyTo(intArr, 1);
      Console.WriteLine("\nQueue (Updated)");
      foreach(int i in queue) {
         Console.WriteLine(i);
      }
      Console.WriteLine("\nArray (Updated)");
      foreach(int i in intArr) {
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

Count of elements = 3
Queue...
100
200
300
Does the queue has element 500? = False
Queue (Updated)
100
200
300
Array (Updated)
1
100
200
300
0

Example

Let us now 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("Tim");
      queue.Enqueue("Jack");
      queue.Enqueue("Nathan");
      queue.Enqueue("Tom");
      queue.Enqueue("David");
      queue.Enqueue("Mark");
      Console.Write("Count of elements = ");
      Console.WriteLine(queue.Count);
      Console.WriteLine("Queue...");
      foreach(string i in queue) {
         Console.WriteLine(i);
      }
      string[] strArr = new string[10];
      strArr[0] = "AB";
      strArr[1] = "BC";
      strArr[2] = "DE";
      strArr[3] = "EF";
      queue.CopyTo(strArr, 1);
      Console.WriteLine("\nQueue (Updated)");
      foreach(string i in queue) {
         Console.WriteLine(i);
      }
      Console.WriteLine("\nArray (Updated)");
      foreach(string i in strArr) {
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

Count of elements = 6
Queue...
Tim
Jack
Nathan
Tom
David
Mark
Queue (Updated)
Tim
Jack
Nathan
Tom
David
Mark
Array (Updated)
AB
Tim
Jack
Nathan
Tom
David
Mark
raja
Published on 04-Dec-2019 09:35:20
Advertisements