|
|
Question : PowerShell - Array of arrays
|
|
I have data in a pipeline from which I want to create an array of arrays like, for example: (a, XXa), (b, XXb), (c, XXc) I don't want to use a pre-declared multi-dimensional array because it is messy and I don't know in advance how big it will need to be.
This code does not work - is gives a length of 6 $arrayOfArrays = ("a","b","c") | %{($_, "XX$_")} # Check if it worked: "arrayOfArrays[2] = " + $arrayOfArrays[2] "Length = " + $arrayOfArrays.length
This code works but it is messy: $tmp = @(1) $arrayOfArrays = @()
("a","b","c") | %{ $tmp[0] = ($_, "XX$_"); $arrayOfArrays += $tmp;} # Check if it worked: "arrayOfArrays[2] = " + $arrayOfArrays[2] "Length = " + $arrayOfArrays.length
Is there a better way?
|
Answer : PowerShell - Array of arrays
|
|
Two fellow MVPs provided this explaination (Kirk and Karl)
###################################### The pipeline (and certian other operations) will try to Strip an array(or any collection/Ienumerable), so that it can push it down the pipeline one item at a time.. the , just wraps something into an array.. so often if you already have an array you use the , to put that array inside an array , so that when the pipeline strips it, it just pushes the original array down the pipeline as ONE item. look at this ,,,( 1..5) You will notice the 5 element array is inside a one element array which is inside a one element array which is inside a one element array.. now run each of these ,,,( 1..5) | % { $_ } ,,,(1..5) | % { $_ } | % { $_ } ,,,(1..5) | % { $_ } | % { $_ } | % { $_ } you'll see that the "container arrays" get strip at each pipeline level, with the Last line, having been run through a pipeline boundary 3 times, you get the final container array stripped, and the pipeline gets the the items stripped and pushed down one at a time..
|
|
|
|
|