Csharp/CSharp Tutorial/Data Structure/ArrayList ToArray
Convert an ArrayList into an array
<source lang="csharp">using System; using System.Collections;
class MainClass {
public static void Main() { ArrayList al = new ArrayList(); // Add elements to the array list. al.Add(1); al.Add(2); al.Add(3); al.Add(4); Console.Write("Contents: "); foreach(int i in al) Console.Write(i + " "); Console.WriteLine(); // Get the array. int[] ia = (int[]) al.ToArray(typeof(int)); int sum = 0; // sum the array for(int i=0; i<ia.Length; i++) sum += ia[i]; Console.WriteLine("Sum is: " + sum); }
}</source>
Contents: 1 2 3 4 Sum is: 10
Convert user-defined objects in an ArrayList to an array
<source lang="csharp">using System; using System.Collections; using System.Collections.Specialized; class MyClass{
public string MyName="";
} class MainClass {
static void Main(string[] args) { ArrayList classList = new ArrayList(); classList.AddRange(new MyClass[] { new MyClass(), new MyClass(), new MyClass()}); Console.WriteLine("Items in List: {0}", classList.Count); // Get object array from ArrayList & print again. object[] arrayOfMyClasss = classList.ToArray(); for(int i = 0; i < arrayOfMyClasss.Length; i++) { Console.WriteLine("MyClass name: {0}", ((MyClass)arrayOfMyClasss[i]).MyName); } }
}</source>
Items in List: 3 MyClass name: MyClass name: MyClass name:
Use ArrayList.ToArray to create a strongly typed string array from the contents of the collection
<source lang="csharp">using System; using System.Collections; class MainClass {
public static void Main(string[] args) { // 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"); string[] array3 = (string[])list.ToArray(typeof(String)); Console.WriteLine("Array 3:"); foreach (string s in array3) { Console.WriteLine("\t{0}", s); } }
}</source>
Array 3: B G J S M