LINQ可以在PowerShell中使用吗? [英] Can LINQ be used in PowerShell?

查看:86
本文介绍了LINQ可以在PowerShell中使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PowerShell中使用LINQ.由于PowerShell是基于.NET Framework构建的,因此这似乎应该是完全可能的,但是我无法使其正常工作.例如,当我尝试以下(人为)代码时:

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

我收到以下错误:

找不到"Where"的重载,并且参数计数为"2".

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

不要介意使用Where-Object可以完成此操作.这个问题的重点不是找到在PowerShell中执行此操作的惯用方式.如果我可以使用LINQ,则在PowerShell中完成某些任务会容易很多年.

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.

推荐答案

您的代码的问题是PowerShell无法确定ScriptBlock实例({ ... })应该转换为哪种特定的委托类型. 因此,它无法为 Where方法.而且它也没有语法来明确指定通用参数.若要解决此问题,您需要自己将ScriptBlock实例强制转换为正确的委托类型:

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

为什么[Func[object, bool]]有效,但[Func[int, bool]]不起作用?

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

因为您的$data[object[]],而不是[int[]],因为PowerShell默认情况下会创建[object[]]数组;但是,您可以显式构造[int[]]实例:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆