如何在PowerShell中“压缩”两个数组?

时间:2022-09-06 15:35:55

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).

我想压缩两个数组,比如Ruby如何做,但是在PowerShell中。这是一个假设的运算符(我知道我们可能正在谈论某种愚蠢的管道,但我只想展示一个示例输出)。

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

1 个解决方案

#1


6  

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.

没有任何内置功能,可能不建议“自己动手”功能。所以,我们将采用LINQ Zip方法并将其包装起来。

[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'

#1


6  

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.

没有任何内置功能,可能不建议“自己动手”功能。所以,我们将采用LINQ Zip方法并将其包装起来。

[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'