Copy a Collection to an Array

We can use ICollection.CopyTo method implemented by all collection classes to convert collection to an Array.

ArrayList, Stack, and Queue collections also has the ToArray method.


using System;
using System.Collections;

class MainClass
{
    public static void Main()
    {
        // Create a new ArrayList and populate it. 
        ArrayList list = new ArrayList(5);
        list.Add("B");
        list.Add("G");
        list.Add("J");
        list.Add("S");
        list.Add("M");

        // Create a string array and use the ICollection.CopyTo method 
        // to copy the contents of the ArrayList. 
        string[] array1 = new string[list.Count];
        list.CopyTo(array1, 0);
        // Use ArrayList.ToArray to create an object array from the 
        // contents of the collection. 
        object[] array2 = list.ToArray();

        // Use ArrayList.ToArray to create a strongly typed string 
        // array from the contents of the collection. 
        string[] array3 = (string[])list.ToArray(typeof(String));

        // Display the contents of the three arrays. 
        Console.WriteLine("Array 1:");
        foreach (string s in array1)
        {
            Console.WriteLine("\t{0}", s);
        }

        Console.WriteLine("Array 2:");
        foreach (string s in array2)
        {
            Console.WriteLine("\t{0}", s);
        }

        Console.WriteLine("Array 3:");
        foreach (string s in array3)
        {
            Console.WriteLine("\t{0}", s);
        }

    }
}

The output:


Array 1:
	B
	G
	J
	S
	M
Array 2:
	B
	G
	J
	S
	M
Array 3:
	B
	G
	J
	S
	M
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.