现在的位置: 首页 > 综合 > 正文

Converting ArrayList to Array / Array to ArrayList C#

2012年01月17日 ⁄ 综合 ⁄ 共 2293字 ⁄ 字号 评论关闭
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.

抱歉!评论已关闭.