我该如何“压缩"在PowerShell中的两个数组? [英] How can I "zip" two arrays in PowerShell?

查看:80
本文介绍了我该如何“压缩"在PowerShell中的两个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

没有内置的功能,因此不建议您滚动自己的"功能.因此,我们将采用LINQ Zip方法并将其包装.

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

您可以简单地称呼它:

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'

这篇关于我该如何“压缩"在PowerShell中的两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆