Converting ArrayList to Array / Array to ArrayList C#

This article explains the easiest way to convert Array  object  into ArrayList and the reverse.  Author: Aldwin Enriquez 

aldwin.net    

Posted Date: 
06  Dec,  2005   
.NET Classes used : 


System.Collections.ArrayList 
 
 
Introduction

Manipulating arrays 
is  one among the most common task  in  an application development. There were times you need to use array of objects to use the power of  object  properties and there were times you might like to use an ArrayList  for  flexibility. Sometimes switching back and forth between these two objects becomes a royal pain  in  the neck. This article leads you the way on how to  do  things better




The hard way

Mostly beginners 
do   this  conversion manually. In the  case  of converting from  object  array into an ArrayList, one might instantiate a  new  ArrayList then iterates through each  object   in  the array and add it to the ArrayList.

Lets assume we have an 
object  called Person. Typically here  is  what  is  commonly done:

Person[] personArray 
=  myPerson.GetPersons();

ArrayList personList 
=   new  ArrayList();
foreach (Person objPerson  in  personArray)
{
personList.Add(objPerson);
}


And creating an 
object  array from an ArrayList might be coded  this  way
Person[] personArrayFromList 
=   new  Person[personList.Count];
int  arrayCounter  =   0 ;
foreach (Person objPerson  in  personList)
{
personArrayFromList.SetValue(objPerson,arrayCounter
++);
}






The easy one

But why 
do  it that way  while  we can just use built - in  methods within the .NET classes.

To perform conversions from 
object  array to an ArrayList use the ArrayList.Adapter method. This method takes an IList to be wrapped into an ArrayList. Now the procedure above can be coded like  this :
Person[] personArray 
=  myPerson.GetPersons();

ArrayList personList 
=  ArrayList.Adapter(personArray);

To perform conversions from ArrayList  to 
object  array use the ArrayList.ToArray method. Now the procedure above can be coded like  this :
Person[] personArrayFromList 
=  (Person[])personList.ToArray( typeof (Person));

Don’t forget the casting preceding the arraylist.ToArray method, otherwise you’ll 
get  an error message at compile time saying you can’t convert that arraylist into Person array.




Summary

So next time you convert an 
object  array to arraylist use the  static  ArrayList.Adapter method and doing the reverse use the ToArray method of the arraylist  object .

你可能感兴趣的:(ArrayList)