CFou
CFou

Reputation: 1180

Generic List Insert method

While I have no problem when adding arrays to a generic list, I am facing issues when trying to insert them :

$myList = [System.Collections.Generic.List[string]]::new()
[string[]]$myArr1 = "one", "two", "three"
[string[]]$myArr2 = "four", "five", "six"
$myList.AddRange($myArr2)
$myList.Insert(0, $myArr1)
$myList

is returning

one two three
four
five
six

while

one
two
three
four
five
six

is awaited. I have tried $myList.Insert(0, {$myArr1}.Invoke()) without any success.

Facing another issue :

$mypart = [System.Collections.Generic.List[CimInstance]]::new()
[CimInstance[]]$disk0 = Get-Partition -DiskNumber 0
[CimInstance[]]$disk1 = Get-Partition -DiskNumber 1
$mypart.AddRange($disk1)
$mypart.Insert(0, $disk0)
$mypart

Here, Insert method throw an error "overload with 2 arguments not found".

Thanks for helping :)

Upvotes: 1

Views: 1381

Answers (1)

mklement0
mklement0

Reputation: 437608

Just like .AddRange() (rather than just .Add()) is required to append the elements of a collection (individually) in a single operation, you need to use .InsertRange() (rather than just .Insert()) to do the same for an insert operation.

The reason that the attempting .Insert() with a [string] array did not fail is that PowerShell quietly converted the string array to a single string, by space-concatenating the elements (as "$('one', 'two')" would). For a [CimInstance] array, no such conversion can be performed, which is why an error occurs.

Upvotes: 3

Related Questions