Calling static generic LINQ extension method in PowerShell

↘锁芯ラ 提交于 2020-01-05 08:17:17

问题


One can call many LINQ methods in PowerShell with this simple notation:

[int[]] $numbers = 1..10000
[Linq.Enumerable]::Sum($numbers)

It is even a relatively simple matter to include a lambda in a call:

[Func[int,int]] $delegate = { $n = $args[0]; if ($n % 3) { $n } else { -$n } }
[Linq.Enumerable]::Sum($numbers, $delegate)

What I am wondering, though, is how to call a generic LINQ method from PowerShell: is it even possible? I found this SO question that seems to indicate one can, but I have not determined how to apply that info to LINQ. (Plus, the fact that that is old information, it is quite possible that with PS version 5 there is a cleaner way to do it.)

So how could one call [Linq.Enumerable]::Cast<T>(...) or [Linq.Enumerable]::OfType<T>(...) properly in PowerShell?

2017.05.10 Update

OK, so based on @Mathias comment, let's stick with MakeGenericMethod. In C#, this incantation works:

var ofTypeForString = typeof(System.Linq.Enumerable).GetMethod("OfType").MakeGenericMethod(typeof(string));
var stuff = new object[] { 1.2, "abc", "def" };
var results = ofTypeForString.Invoke(null, new[] { stuff });

The piece I am still missing is how to translate typeof(System.Linq.Enumerable) to PowerShell. I thought that at least one of these should work but they all return null:

[System.Type]::GetType("System.Linq.Enumerable")
[System.Type]::GetType("Linq.Enumerable")
[System.Type]::GetType("Enumerable")

I am sure I am missing something simple; suggestions?


回答1:


Yes, both PetSerAl and ejohnson's comments are correct, of course; I just had a mental block for some reason. So here is the complete solution for those who may be interested:

$stringType = "".GetType() # set to your target type
$ofTypeForString =
        [Linq.Enumerable].GetMethod("OfType").MakeGenericMethod($stringType)
$stuff = @("12345", 12, "def")
# The last comma below wraps the array arg $stuff within another array
$ofTypeForString.Invoke($null, (,$stuff)) 


来源:https://stackoverflow.com/questions/43883071/calling-static-generic-linq-extension-method-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!