linqpowershell

Can LINQ be used in PowerShell?


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. For example, when I try the following (contrived) code:

$data = 0..10

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

I get the following error:

Cannot find an overload for "Where" and the argument count: "2".

Never mind the fact that this could be accomplished with Where-Object. The point of this question is not to find an idiomatic way of doing this one operation in PowerShell. Some tasks would be light-years easier to do in PowerShell if I could use LINQ.


Solution

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