C#中的Queue.CopyTo()方法用于从指定的数组索引处开始,将Queue元素复制到现有的一维数组。
语法如下-
public virtual void CopyTo (Array arr, int index);
上面的参数arr是一维数组,它是从Queue复制的元素的目的地。index参数是开始复制的数组中从零开始的索引。
现在让我们看一个例子-
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); } } }
输出结果
这将产生以下输出-
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
现在让我们来看另一个示例-
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); } } }
输出结果
这将产生以下输出-
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