Arraylist to List 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/

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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.

Method 3

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.

Method 4

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x