How to convert an ArrayList to a strongly typed generic list without using a foreach?

James Lawruk picture James Lawruk · Apr 24, 2009 · Viewed 54.2k times · Source

See the code sample below. I need the ArrayList to be a generic List. I don't want to use foreach.

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;    

Answer

JaredPar picture JaredPar · Apr 24, 2009

Try the following

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

This will only work though using the C# 3.5 compiler because it takes advantage of certain extension methods defined in the 3.5 framework.