与 LINQ 的 All() 等效的 PowerShell 是什么?

Jam*_* Ko 2 linq powershell

我正在尝试测试 PowerShell 中数组中所有项的条件是否为真(类似于 LINQ 的All函数)。除了编写手动 for 循环外,在 PowerShell 中执行此操作的“正确”方法是什么?

具体来说,是我试图从 C# 翻译的代码:

public static IEnumerable<string> FilterNamespaces(IEnumerable<string> namespaces)
  => namespaces
     .Where(ns => namespaces
       .Where(n => n != ns)
         .All(n => !Regex.IsMatch(n, $@"{Regex.Escape(ns)}[\.\n]")))
     .Distinct();
Run Code Online (Sandbox Code Playgroud)

Fro*_* F. 6

我不会在 powershell 中重新创建 C# 代码,而是以 PowerShell 的方式进行。前任:

function Filter-Namespaces ([string[]]$Namespaces) {
  $Namespaces | Where-Object {
    $thisNamespace = $_;
    (
      $Namespaces | ForEach-Object { $_ -match "^$([regex]::Escape($thisNamespace))\." }
    ) -notcontains $true
  } | Select-Object -Unique
}

Filter-Namespaces -Namespaces $values

System.Windows.Input
System.Windows.Converters
System.Windows.Markup.Primitives
System.IO.Packaging
Run Code Online (Sandbox Code Playgroud)

但是,要回答您的问题,您可以通过手动方式进行:

$values = "System",
"System.Windows",
"System.Windows.Input",
"System.Windows.Converters",
"System.Windows.Markup",
"System.Windows.Markup.Primitives",
"System.IO",
"System.IO.Packaging"

($values | ForEach-Object { $_ -match 'System' }) -notcontains $false

True
Run Code Online (Sandbox Code Playgroud)

或者你可以为它创建一个函数:

function Test-All {
    [CmdletBinding()]
    param(
    [Parameter(Mandatory=$true)]
    $Condition,
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    $InputObject
    )

    begin { $result = $true }
    process {
        $InputObject | Foreach-Object { 
            if (-not (& $Condition)) { $result = $false }
        }
    }
    end { $result }
}

$values = "System",
"System.Windows",
"System.Windows.Input",
"System.Windows.Converters",
"System.Windows.Markup",
"System.Windows.Markup.Primitives",
"System.IO",
"System.IO.Packaging"

#Using pipeline
$values | Test-All { $_ -match 'System' }

#Using array arguemtn
Test-All -Condition { $_ -match 'System' } -InputObject $values
#Using single value argument
Test-All -Condition { $_ -match 'System' } -InputObject $values[0]
Run Code Online (Sandbox Code Playgroud)

或者您可以编译 C# 代码或使用Add-Type.