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/
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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With