arrays - 如何在 PowerShell 中 "zip"两个数组?

标签 arrays powershell

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

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

最佳答案

没有任何内置功能,可能不建议“推出自己的”功能。因此,我们将采用 LINQ Zip 方法并将其包装起来。

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

这有效,但随着时间的推移工作并不愉快。我们可以包装函数(并将其包含在我们的配置文件中?)。
function Select-Zip {
    [CmdletBinding()]
    Param(
        $First,
        $Second,
        $ResultSelector = { ,$args }
    )

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

你可以简单地称之为:
PS> Select-Zip -First 1, 2, 3 -Second 'A', 'B', 'C'
1
A
2
B
3
C

使用非默认结果选择器:
PS> Select-Zip -First 1, 2, 3 -Second 'A', 'B', 'C' -ResultSelector { param($a, $b) "$a::$b" }
1::A
2::B
3::C

我将管道版本作为练习留给精明的读者:)
PS> 1, 2, 3 | Select-Zip -Second 'A', 'B', 'C'

关于arrays - 如何在 PowerShell 中 "zip"两个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43122000/

相关文章:

javascript - 将值赋给数组内的数组

php - 数组中的嵌套页面 - PHP

javascript - 在内存层面,JS中创建对象和创建类实例有区别吗?

PowerShell:检查文件夹是否有更改,如果有,则发送电子邮件

javascript - 如何将对象数组中的对象作为逗号分隔对象列表传递给函数?

c++ - 将用户输入的空间存储在 char 数组中

c# - "An error occurred when loading the system Windows PowerShell snap-ins"

powershell - 使用 PowerShell 替换 CSV 中的空值

powershell - Test-Path-叶意义

arrays - 将相同类型的命令行参数读入Powershell中的数组/哈希