views:

2564

answers:

2

See the code sample below. I need the ArrayList to be a generic List.

ArrayList arrayList = GetArrayListOfInts();  
List<int> intList = new List<int>();  

//Can this be foreach be condensed into one line?  
foreach (int number in arrayList)  
{  
    intList.Add(number);  
}  
return intList;
+15  A: 

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.

JaredPar
While I've certainly used this before myself, I'm considering boxing/unboxing. Won't that retract from performance? Sometimes I find that pretty code is at the expense of speed and resources...
J. Steen
That's just a consequence of putting it in an ArrayList in the first place. Just casting every member back to an int is pretty much the best you can do performance-wise.
mquander
@mquander, true, true... I just realized the for-loop in the OP's post does just that as well. =)
J. Steen
Somehow, I missed Cast<> in the System.Linq namespace. I wrote my own extension method that I can remove now. Thanks!
Brian Genisio
+5  A: 

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

List<int> newList = new List<int>(arrayList.ToArray(typeof(int)));
mquander
Why is this not working for me?
TheMachineCharmer
I did `arrayList.ToArray(typeof(int)) as int[]` and then it worked thanks! +1
TheMachineCharmer