Search code examples
c#powershelllinq

How to use the fully qualified name of a method?


I need an embedded C# code snippet for my Powershell script like this:

$myArray = @(7,6,5,4)

Add-Type @"
public static int[] indexOfMin(int[] arr){
    int min = arr.Linq.Min();
    return new int[] {min, Array.IndexOf(arr, min)};
}
"@ -name my -Namespace System

$minValue, $minIndex = [my]::indexOfMin($myArray)

I am looking for a simple way to specify the Min()-method from Linq without having the additional lines for the using-block and the class-wrapper.

Is there any simple way to specify the assembly of that single call of Min()?


Solution

  • Use the -UsingNamespace parameter to include a namespace reference to System.Linq so the compiler can resolve the .Min() extension method:

    $myArray = @(7,6,5,4)
    
    Add-Type @"
    public static int[] indexOfMin(int[] arr){
        int min = arr.Min();
        return new int[] {min, Array.IndexOf(arr, min)};
    }
    "@ -name my -Namespace System -UsingNamespace System.Linq
    
    $minValue, $minIndex = [my]::indexOfMin($myArray)