The Queue<T>
generic class in the System.Collections.Generic
namespace provides the ToArray()
method, which can be used to copy a queue to a new array in C#.
public T[] ToArray ();
This operation does not change the state of Queue<T>
.
A new array is created, the queue elements are copied to it, and the array is returned.
The elements are ordered in the new array in the same way as the order of the elements from the start of Queue<T>
to the end.
This is an operation, where n is count of the elements in the Queue<T>
.
In the following example, we have created a queue of strings to store month names and have added the names of a few months to it. After we add the elements, we print all the elements present in the queue.
After this, we created a new array of strings, queueCopy
, and copied the queue elements to it with the ToArray()
method.
We then print the elements of the array and observe that both the queue and the array contain the same elements in the same order.
using System; using System.Collections.Generic; class QueueConverter { static void Main() { Queue<string> months = new Queue<string>(); months.Enqueue("January"); months.Enqueue("February"); months.Enqueue("March"); months.Enqueue("April"); months.Enqueue("May"); months.Enqueue("June"); Console.WriteLine("Queue Items : {0}", string.Join(",", months.ToArray())); string[] queueCopy = months.ToArray(); Console.WriteLine("Array Items : {0}", string.Join(",", queueCopy)); } }
RELATED TAGS
CONTRIBUTOR
View all Courses