Convert ArrayList to array

In this chapter you will learn:

  1. How to convert ArrayList to array
  2. Cast to int and convert to list

Convert to array

The following code demonstrates the following methods: CopyTo(), ToArray(), ToArray(typeof(String)).

using System; /*from   j  a v  a2 s  . c  o  m*/
using System.Collections;
class MainClass
{
    public static void Main()
    {
        ArrayList list = new ArrayList(5);
        list.Add("B");
        list.Add("G");
        list.Add("J");
        list.Add("S");
        list.Add("M");

        string[] array1 = new string[list.Count];
        list.CopyTo(array1, 0);


        object[] array2 = list.ToArray();
        string[] array3 = (string[])list.ToArray(typeof(String));
        
        foreach (string s in array1)
        {
            Console.WriteLine(s);
        }
        foreach (string s in array2)
        {
            Console.WriteLine(s);
        }
        foreach (string s in array3)
        {
            Console.WriteLine(s);
        }
     }
}

Cast to int and convert to list

If you import the System.Linq namespace, you can convert an ArrayList to a generic List by calling Cast and then ToList:

using System;//from  j  a v a 2s.c  om
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Sample
{
    public static void Main()
    {
        ArrayList al = new ArrayList();
        al.AddRange(new[] { 1, 5, 9 });
        List<int> list = al.Cast<int>().ToList();
        
        foreach(int i in list){
           Console.WriteLine(i);
        }
    }

}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to add elements to LinkedList