. 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 articleArticleTeach 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:
Person [] personarray = Myperson. getpersons ();
Arraylist personlist = New Arraylist ();
Foreach (Person objperson In Personarray)
{
Personlist. Add (objperson );
}
You can also use this method to create an object array from an arraylist:
Person [] personarrayfromlist = New Person [personlist. Count];
Int Arraycounter = 0 ;
Foreach (Person objperson In Personlist)
{
Personarrayfromlist. setvalue (objperson, arraycounter ++ );
}
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:
Person [] personarray = Myperson. getpersons ();
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:
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.
Summary
To sum up, 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.