Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
queue
array
communitycreator

How to copy a queue to an existing array in C#

Surabhi Sharma

The Queue<T> generic class in the System.Collections.Generic namespace provides the CopyTo() method, which can be used to copy a queue to an existing array at a specified index in C#.

Syntax

public void CopyTo (T[] array, int arrayIndex);

This method takes as input a one-dimensional array where the elements will be copied from Queue<T>, and an index at which the copying begins.

This method throws an exception if:

  • The input array is null.
  • The input index is less than zero.
  • The number of elements in Queue<T> is greater than the total number of spaces available in the destination array from the specified index to the end of the array.

Things to note

  • This method works on one-dimensional arrays.

  • This operation does not change the state of the queue.

  • The elements are ordered in the array in the same way as the order of the elements from the start of the queue to the end.

  • This is an O(n)O(n) operation, where n is the count of the elements in the queue.

Copying a C# queue to an existing array at a index

Code

In this example, we create a queue of strings to store month names, and add the names of four months to it: March, April, May and June. After we add the elements, we print all the elements present in the queue.

After this, we create a new array of queueCopy strings with a size of ten elements that has two elements in it: January and February. We now copy all the queue elements to this array with the CopyTo() method, starting from index two.

months.CopyTo(queueCopy,2);

We then print the elements of the array, and the array contains the queue elements in the same order from the specified index.

using System;
using System.Collections.Generic;

class QueueConverter
{
    static void Main()
    {
        Queue<string> months = new Queue<string>();
        months.Enqueue("March");
        months.Enqueue("April");
        months.Enqueue("May");
        months.Enqueue("June");

        Console.WriteLine("Queue Items : {0}", string.Join(",", months.ToArray()));
        string[] queueCopy = new string[10];
        queueCopy[0] = "January";
        queueCopy[1] = "February";
        Console.WriteLine("Array Items before Copy : {0}", string.Join(",", queueCopy));
        months.CopyTo(queueCopy,2);
        Console.WriteLine("Array Items after Copy : {0}", string.Join(",", queueCopy));


    }
}

RELATED TAGS

c#
queue
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring