Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the PowerShell equivalent to LINQ's Select?

Tags:

powershell

(I know this sounds like a duplicate, but hear me out)

Given the following code, if Select-Object where equivalent to LINQ's Select, the output should be @("o", "n", "e")

"one", "two" | %{$_.GetCharArray()} | select -first 1

However, since the output is "o", this tells me that Select-Object actually acts the same as LINQ's SelectMany rather than Select.

So many question is: Is there a direct equivalent to Select in PowerShell (ie. one that would not merge the collections in the pipeline)

like image 856
Richard Szalay Avatar asked Jan 17 '23 18:01

Richard Szalay


1 Answers

This is not about select but rather about unrolling arrays obtained by ToCharArray() and sent to the pipeline. In order to get expected results using standard select we should prevent unrolling. This is typically done by using the unary operator , which returns an array with a single item. In our case these items are arrays theselves. They are not unrolled, they are sent to the pipeline as they are. Thus, select -first 1 selects the first item which is an array with 3 items.

"one", "two" | %{, $_.ToCharArray()} | select -first 1

This gives 3 items: o, n, e.

like image 136
Roman Kuzmin Avatar answered Jan 25 '23 22:01

Roman Kuzmin