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 wi开发者_如何学运维th 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.
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)));
精彩评论