In C #, convert arraylist to array or convert array to arraylist.
Address: http://www.dotnetspider.com/kb/Article1709.aspx
Dec 2005 by Aldwin Enriquez
Narrasoft Philippines.
Overview
This articleArticleExplains how to use the simplest method to convert an array into an arraylist and convert it in the opposite way.
. Net class used
System. Collections. arraylist
Introduction
The operation array is one of the most common tasks in application development. Sometimes you need to use a group of objects to obtain the attributes of the operation object, and sometimes you use arraylist for greater flexibility. It is very painful to make a choice between the two methods. This article teaches you how to better solve this problem.
Stupid Method
Almost all beginners use manual transformations. From the array of converted objects to the arraylist, one method may be to initialize an arraylist object first, and then add each object in the array to the arraylist again.
Let's assume that we have an object called person. The following is a common practice:
1 Person [] personarray = Myperson. getpersons ();
2 Arraylist personlist = New Arraylist ();
3 Foreach (Person objperson In Personarray)
4 {
5Personlist. Add (objperson );
6}
You can also use this method to create an object array from an arraylist:
1 Person [] personarrayfromlist = New Person [personlist. Count];
2 Int Arraycounter = 0 ;
3 Foreach (Person objperson In Personlist)
4 {
5Personarrayfromlist. setvalue (objperson, arraycounter++);
6}
Simple Method
But why don't we use the built-in methods of the. NET class library to implement this function?
You can use the arraylist. Adapter method to convert an object array to an arraylist. This method wraps an ilist in an arraylist. Now the aboveCodeYou can write it as follows:
1 Person [] personarray = Myperson. getpersons ();
2 Arraylist personlist = Arraylist. adapter (personarray );
You can use the arraylist. toarray method to convert an arraylist to an object array. Now the above Code can be written:
1 Person [] personarrayfromlist = (Person []) personlist. toarray ( Typeof (Person ));
Do not forget to implement forced type conversion before calling the arraylist. toarray method. Otherwise, an error will be prompted during compilation, indicating that you cannot convert an arraylist to an array of person objects.
conclusion
In summary, the next time you want to convert an object array to arraylist, you can use the static method arraylist. adapter; or you can use the arraylist of the arraylist object. toarray method to implement the opposite conversion.