Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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("
Queue (Updated)");
foreach(int i in queue) {
Console.WriteLine(i);
}
Console.WriteLine("
Array (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 −
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("
Queue (Updated)");
foreach(string i in queue) {
Console.WriteLine(i);
}
Console.WriteLine("
Array (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
Advertisements