Convert ArrayList to object array
I need to create an ArrayList to and array of entity objects. In this sample, an array of Person objects. I need to build the array dynamically, and I'd like to use the intrinsic .Net System.Collection classes. In this sample, we'll use an ArrayList object.
Once we've created the ArrayList and added all the people to it, we want to convert it to an array of Person objects. The cast is a little wierd, and took me a while to figure out...
// Create an ArrayList and add some people to it
ArrayList peopleList = new ArrayList();
peopleList.Add(new Person("Mickey", "Mouse"));
peopleList.Add(new Person("Minny", "Mouse"));
peopleList.Add(new Person("Donald", "Duck"));
// Finally, convert it to a typed array object
Person[] peopleArray = (Person[]) peopleList.ToArray(typeof(Person));
ArrayList peopleList = new ArrayList();
peopleList.Add(new Person("Mickey", "Mouse"));
peopleList.Add(new Person("Minny", "Mouse"));
peopleList.Add(new Person("Donald", "Duck"));
// Finally, convert it to a typed array object
Person[] peopleArray = (Person[]) peopleList.ToArray(typeof(Person));
No comments:
Post a Comment