LINQ 可以在 PowerShell 中使用吗? [英] Can LINQ be used in PowerShell?
问题描述
我正在尝试在 PowerShell 中使用 LINQ.看起来这应该是完全可能的,因为 PowerShell 是建立在 .NET Framework 之上的,但我无法让它工作.例如,当我尝试以下(人为的)代码时:
$data = 0..10[System.Linq.Enumerable]::Where($data, { param($x) $x -gt 5 })
我收到以下错误:
<块引用>找不到Where"和参数计数的重载:2".
没关系,这可以通过 Where-Object
来完成.这个问题的重点不是要找到在 PowerShell 中执行此操作的惯用方法.如果我可以使用 LINQ,那么在 PowerShell 中完成某些任务会轻松数光年.
您的代码的问题是 PowerShell 无法决定 ScriptBlock
实例 ({ ...}
) 应该被强制转换.因此,它无法为 Where
方法.而且它也没有明确指定泛型参数的语法.要解决此问题,您需要自己将 ScriptBlock
实例强制转换为正确的委托类型:
$data = 0..10[System.Linq.Enumerable]::Where($data, [Func[object,bool]]{ param($x) $x -gt 5 })
<块引用>
为什么 [Func[object, bool]]
有效,而 [Func[int, bool]]
无效?
因为您的 $data
是 [object[]]
,而不是 [int[]]
,因为 PowerShell 创建了 [object[]]
默认为数组;但是,您可以显式构造 [int[]]
实例:
$intdata = [int[]]$data[System.Linq.Enumerable]::Where($intdata, [Func[int,bool]]{ param($x) $x -gt 5 })
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.
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 })
这篇关于LINQ 可以在 PowerShell 中使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!