Curtis White
Curtis White

Reputation: 6353

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/

Upvotes: 12

Views: 12902

Answers (4)

Jerod Houghtelling
Jerod Houghtelling

Reputation: 4867

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.

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460098

This works in Framework <3.5 too:

Dim al As New ArrayList()
al.Add(1)
al.Add(2)
al.Add(3)
Dim newList As New List(Of Int32)(al.ToArray(GetType(Int32)))

C#

List<int> newList = new List<int>(al.ToArray(typeof(int)));

Upvotes: 0

Ryan Bennett
Ryan Bennett

Reputation: 3432

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.

Upvotes: 2

Adam Robinson
Adam Robinson

Reputation: 185643

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);

Upvotes: 26

Related Questions