What is the PowerShell equivalent to LINQ’s Select?

Question:

(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")

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)

Answer:

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.

This gives 3 items: o, n, e.

Source:

What is the PowerShell equivalent to LINQ’s Select? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply