none
convert ArrayList to string array

    Question

  • Hi all,
    here is my simple problem:

     
    ParserQueue is ArrayList with many elements, every one of which is arraylist;  
    cols is another ArrayList which get subelement from ParserQueue.  
    then:  
     
    cols.Add(ParserQueue[i]);  
    string[] scols = (string[])cols.ToArray(typeof(string));  
     
    generates:  At least one element in the source array could not be cast down to the destination array type. 'System.InvalidCastException' 

    How to do the right convertion from ArrayList to string array.
    Actually ParserQueue[i] is ArrayList of strings, which has to be transferred to simple string array;

    also when I have ArrayList of ArrayLists, how to loop through all elemnts in a given sub-arraylist ?
    • Edited by Hof Noff Sunday, November 16, 2008 10:34 PM
    Sunday, November 16, 2008 9:14 PM

Answers

  •  
    1 using System;  
    2 using System.Collections.Generic;  
    3 using System.Collections;  
    4  
    5 namespace ConsoleApplication1 {  
    6     class Program {  
    7         static void Main(string[] args) {  
    8             ArrayList list1 = new ArrayList();  
    9  
    10             for (int i = 0; i < 10; i++) {  
    11                 ArrayList list2 = new ArrayList();  
    12                 for (int j = 0; j < i + 5; j++) {  
    13                     list2.Add(i.ToString() + "." + j.ToString());  
    14                 }  
    15                 list1.Add(list2);  
    16             }  
    17  
    18             String[] s = ArrayListArrayListToStringArray(list1);  
    19  
    20             Console.WriteLine("There are {0} strings in the list", s.Length);  
    21  
    22             foreach (String str in s) {  
    23                 Console.WriteLine(str);  
    24             }  
    25  
    26             Console.ReadLine();  
    27         }  
    28  
    29         static String[] ArrayListArrayListToStringArray(ArrayList a) {  
    30             List<String> sl = new List<String>();  
    31  
    32             foreach (ArrayList al in a) {  
    33                 sl.AddRange((String[])al.ToArray(typeof(String)));  
    34             }  
    35  
    36             return sl.ToArray();  
    37         }  
    38     }  
    39

    Ron Whittle
    • Marked as answer by Guo Surfer Thursday, November 20, 2008 7:57 AM
    Sunday, November 16, 2008 11:10 PM