In .Net, how do you convert an ArrayList to a strongly typed shared list without using foreach?

See the sample code below. I need ArrayList be a shared list.

 ArrayList arrayList = GetArrayListOfInts(); List<int> intList = new List<int>(); //Can this foreach be condensed into one line? foreach (int number in arrayList) { intList.Add(number); } return intList; 
+51
arraylist list c # generic-list
Apr 24 '09 at 15:10
source share
3 answers

Try to execute

 var list = arrayList.Cast<int>().ToList(); 

This will only work using the C # 3.5 compiler, as it uses some extension methods defined in the 3.5 framework.

+98
Apr 24 '09 at 15:11
source share

This is inefficient (it makes an unnecessary intermediate array), but is concise and will work on .NET 2.0:

 List<int> newList = new List<int>(arrayList.ToArray(typeof(int))); 
+9
Apr 24 '09 at 15:16
source share

How to use the extension method?

From http://www.dotnetperls.com/convert-arraylist-list :

 using System; using System.Collections; using System.Collections.Generic; static class Extensions { /// <summary> /// Convert ArrayList to List. /// </summary> public static List<T> ToList<T>(this ArrayList arrayList) { List<T> list = new List<T>(arrayList.Count); foreach (T instance in arrayList) { list.Add(instance); } return list; } } 
+4
Feb 22 '11 at 17:30
source share



All Articles