Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arraylist to List<t> using .Net?

How can I convert/dump an arraylist into a list? I'm using arraylist because I'm using the ASP.NET profiles feature and it looked like a pain to store List in profiles.

Note: The other option would be to wrap the List into an own class and do away with ArrayList.

http://www.ipreferjim.com/site/2009/04/storing-generics-in-asp-net-profile-object/

like image 980
Curtis White Avatar asked Aug 02 '10 19:08

Curtis White


3 Answers

The easiest way to convert an ArrayList full of objects of type T would be this (assuming you're using .NET 3.5 or greater):

List<T> list = arrayList.Cast<T>().ToList();

If you're using 3.0 or earlier, you'll have to loop yourself:

List<T> list = new List<T>(arrayList.Count);

foreach(T item in arrayList) list.Add(item);
like image 183
Adam Robinson Avatar answered Nov 16 '22 01:11

Adam Robinson


You can use Linq if you are using .NET 3.5 or greater. using System.Linq;

ArrayList arrayList = new ArrayList();
arrayList.Add( 1 );
arrayList.Add( "two" );
arrayList.Add( 3 );

List<int> integers = arrayList.OfType<int>().ToList();

Otherwise you will have to copy all of the values to a new list.

like image 42
Jerod Houghtelling Avatar answered Nov 15 '22 23:11

Jerod Houghtelling


ArrayList a = new ArrayList();

object[] array = new object[a.Count];

a.CopyTo(array);

List<object> list = new List<object>(array);

Otherwise, you'll just have to do a loop over your arrayList and add it to the new list.

like image 36
Ryan Bennett Avatar answered Nov 15 '22 23:11

Ryan Bennett