Converting arraylist to array/array to arraylist C #
Source: Internet
Author: User
This article explains the easiest way to convert ArrayObjectInto arraylist and the reverse. Author: Aldwin Enriquez
Aldwin.net
Posted Date:06Dec,2005
. Net classes used:
System. Collections. arraylist
Introduction
Manipulating ArraysIsOne among the most common taskInAn application development. There were times you need to use array of objects to use the powerObjectProperties and there were times you might like to use an arraylistForFlexibility. Sometimes switching back and forth between these two objects becomes a royal painInThe neck. This article leads you the way on howDoThings better
The hard way
Mostly beginnersDoThisConversion manually. InCaseOf converting fromObjectArray into an arraylist, one might instantiateNewArraylist then iterates through eachObjectInThe array and add it to the arraylist.
Lets assume we haveObjectCalled person. Typically hereIsWhatIsCommonly done:
And creatingObjectArray from an arraylist might be codedThisWay
Person [] personarrayfromlist=NewPerson [personlist. Count]; IntArraycounter=0; Foreach(Person objpersonInPersonlist) {
Personarrayfromlist. setvalue (objperson, arraycounter++);
}
The easy one
But whyDoIt That WayWhileWe can just use built-InMethods Within the. NET classes.
To perform conversions fromObjectArray 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 likeThis:
Person [] personarray=Myperson. getpersons ();
To perform conversions from arraylistObjectArray use the arraylist. toarray method. Now the procedure above can be coded likeThis:
Person [] personarrayfromlist=(Person []) personlist. toarray (Typeof(Person ));
Don't forget the casting preceding the arraylist. toarray method, otherwise you'llGetAn error message at compile time saying you can't convert that arraylist into person array.
Summary
So next time you convertObjectArray to arraylist useStaticArraylist. Adapter method and doing the reverse use the toarray method of the arraylistObject.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service