Converting Between ArrayList and Array in C# Options

codeling 1298 - 5544
@2015-12-16 13:18:59

From time to time, you may need to do the conversion between ArrayList and Array when you are coding in C#. The following C# code demonstrates how to do these.

 

Converting Array to ArrayList 

ArrayList fileArrayList = = new ArrayList();
string[] files = Directory.GetDirectories(path)
fileArrayList.AddRange(files);

 

Converting ArrayList to Array
 

ArrayList fileArrayList = new ArrayList();
//Populate fileArrayList
...
string[] files = (string[])fileArrayList.ToArray(
typeof(string));

 

Example

public static string[] GetFiles(string path, bool recursive)
{
  ArrayList fileArrayList = new ArrayList();

  DirectoryManager.ValidateDirectoryPath( path);

  if (DirectoryManager.Exists(path))
  {
   fileArrayList.AddRange(Directory.

GetFiles(path));

   if (recursive)
   {
    foreach (string dir in Directory.GetDirectories(path))
    {
     fileArrayList.AddRange(

DirectoryManager.

GetFiles(dir, recursive));
    }
   }
  }

  return (string[])fileArrayList.ToArray(

typeof(string));
}

 
Users browsing this topic
Guest