Can LINQ be used in PowerShell?

前端 未结 5 1024
我寻月下人不归
我寻月下人不归 2020-12-13 23:43

I am trying to use LINQ in PowerShell. It seems like this should be entirely possible since PowerShell is built on top of the .NET Framework, but I cannot get it to work.

5条回答
  •  悲哀的现实
    2020-12-14 00:11

    The problem with your code is that PowerShell cannot decide to which specific delegate type the ScriptBlock instance ({ ... }) should be cast. So it isn't able to choose a type-concrete delegate instantiation for the generic 2nd parameter of the Where method. And it also does't have syntax to specify a generic parameter explicitly. To resolve this problem, you need to cast the ScriptBlock instance to the right delegate type yourself:

    $data = 0..10
    [System.Linq.Enumerable]::Where($data, [Func[object,bool]]{ param($x) $x -gt 5 })
    

    Why does [Func[object, bool]] work, but [Func[int, bool]] does not?

    Because your $data is [object[]], not [int[]], given that PowerShell creates [object[]] arrays by default; you can, however, construct [int[]] instances explicitly:

    $intdata = [int[]]$data
    [System.Linq.Enumerable]::Where($intdata, [Func[int,bool]]{ param($x) $x -gt 5 })
    

提交回复
热议问题