tags:

views:

92

answers:

2

I have an ArrayList that contains Strings and also contains other ArrayLists which may contain Strings or even more ArrayLists.

Is there a simple way to extract all the Strings from this multilevel ArrayList?

I'm assuming some recursion is invloved but I haven't been able to get it to work.

+5  A: 
public static ArrayList FlattenList(ArrayList list) {
   ArrayList l = new ArrayList(); 
   FillList(list, l);
   return l;
}
private static void FillList(ArrayList source, ArrayList listToFill) {
   foreach (object o in source) {
      ArrayList l = o as ArrayList;
      if (l != null)
          FillList(l, listToFill);
      else
          listToFill.Add(o);
   }
}
Mehrdad Afshari
You may want to use 'as' instead of 'is' + cast.
Romain Verdier
@Romain: Good point. I was already editing the answer. Actually, for this code, it isn't just a performance optimization. The old version would throw a `NullReferenceException` if a `null` value exists anywhere in the hierarchy.
Mehrdad Afshari
Thank You ... works perfectly :)
Greycrow
A: 

As an alternative, if you can use generics and iterator blocs then it becomes possible to have a single method:

    public static IEnumerable<string> GetStrings(ArrayList list)
    {
        foreach(var item in list)
        {
            var @string = item as string;
            if (@string != null)
                yield return @string;

            var nestedList = item as ArrayList;
            if(nestedList == null) 
                continue;

            foreach (var childString in GetStrings(nestedList))
                yield return childString;
        }
    }
Romain Verdier