How can I “zip” two arrays in PowerShell?

▼魔方 西西 提交于 2020-11-30 11:58:04

问题


I want to zip two arrays, like how Ruby does it, but in PowerShell. Here's a hypothetical operator (I know we're probably talking about some kind of goofy pipeline, but I just wanted to show an example output).

PS> @(1, 2, 3) -zip @('A', 'B', 'C')
@(@(1, 'A'), @(2, 'B'), @(3, 'C'))

回答1:


There's nothing built-in and it's probably not recommended to "roll your own" function. So, we'll take the LINQ Zip method and wrap it up.

[System.Linq.Enumerable]::Zip((1, 2, 3), ('A', 'B', 'C'), [Func[Object, Object, Object[]]]{ ,$args })

That works, but it's not pleasant to work with over time. We can wrap the function (and include that in our profile?).

function Select-Zip {
    [CmdletBinding()]
    Param(
        $First,
        $Second,
        $ResultSelector = { ,$args }
    )

    [System.Linq.Enumerable]::Zip($First, $Second, [Func[Object, Object, Object[]]]$ResultSelector)
}

And you can call it simply:

PS> Select-Zip -First 1, 2, 3 -Second 'A', 'B', 'C'
1
A
2
B
3
C

With a non-default result selector:

PS> Select-Zip -First 1, 2, 3 -Second 'A', 'B', 'C' -ResultSelector { param($a, $b) "$a::$b" }
1::A
2::B
3::C

I leave the pipeline version as an exercise to the astute reader :)

PS> 1, 2, 3 | Select-Zip -Second 'A', 'B', 'C'



回答2:


# Multiple arrays
$Sizes = @("small", "large", "tiny")
$Colors = @("red", "green", "blue")
$Shapes = @("circle", "square", "oval")

# The first line "zips"
$Sizes | ForEach-Object { $i = 0 }{ @{size=$_; color=$Colors[$i]; shape=$Shapes[$i]}; $i++ } `
 | ForEach-Object { $_.size + " " + $_.color + " " + $_.shape }

Outputs:

small red circle
large green square
tiny blue oval


来源:https://stackoverflow.com/questions/43122000/how-can-i-zip-two-arrays-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!