How can I "pin" two arrays in PowerShell?

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

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

      

+3


source to share


1 answer


There is nothing built-in and it is probably not recommended to "roll your" function. So we will take the LINQ Zip method and complete it.

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

      

It works, but over time it is not pleasant to work with. We can wrap the function (and include it 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 just call it:



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

      

With a result selector other than the default:

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 for the discerning reader :)

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

      

+3


source







All Articles