System.Collections.ArrayList overload

by Lembasts at 2013-02-12 16:37:14


I am looking to make use of the system.collections.arraylist rather than just a collection.

I can do this:
$array= new-object System.Collections.ArrayList
$data=@(Import-CSV “C:\master.csv” | sort computername)

and it populates my arraylist just fine. btw does the addrange guarantee that the data in the arraylist is sorted?

When I looked at the arraylist class is said that a collection can be used as a constructor. So I tried this:
$array= new-object System.Collections.ArrayList(@(Import-CSV “C:\master.csv” | sort computername))

and it appears to take a while to load all the data but then fails with the error:

new-object : Cannot find an overload for “ArrayList” and the argument count: “41983”.
At line:6 char:9
+ $array= new-object System.Collections.ArrayList(@(Import-CSV “C:\master.csv” | s …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:slight_smile: [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

If addrange can use a collection why cant the constructor?
by mjolinor at 2013-02-12 18:04:44
Found this over at SO: … powershell

[code2=powershell]$array = [system.collections.arraylist](import-csv c:\master.csv | sort computername)[/code2]

Seems to work…
by Lembasts at 2013-02-12 18:14:42
Thanks…why the first doesnt work??? Doesnt matter - your one does.
by mjolinor at 2013-02-12 18:36:11
I blame it on PowerShell’s propensity for wanting to “unroll” arrays and collections. Whether you wanted it to or not…
by poshoholic at 2013-02-12 19:02:08
Mjolinor’s right. In the case of the constructor, PowerShell tries to unroll the array and pass the individual items into the constructor. Since there isn’t an ArrayList constructor that accepts 43000+ arguments, the call fails. You could get it to work with the constructor, but you’d have to ensure PowerShell’s unrolling doesn’t cause this problem. Here’s what that would look like (note the ever-so-important comma before the array enclosure that makes this work):
$array= new-object System.Collections.ArrayList(,@(Import-CSV “C:\master.csv” | sort computername))
That said, typecasting like you’re doing now is better in this case.