PowerShell与LINQ的All()等效吗? [英] What is the PowerShell equivalent of LINQ's All()?

查看:61
本文介绍了PowerShell与LINQ的All()等效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图测试PowerShell中数组中所有项目的条件是否为真(类似于LINQ的All函数).如果没有编写手动for循环,那么在PowerShell中执行此操作的正确"方法是什么?

I'm trying to test if a condition is true for all items in an array in PowerShell (similarly to LINQ's All function). What would be the 'proper' way to do this in PowerShell, short of writing a manual for-loop?

具体来说,此处是我要从C#转换的代码:

To be specific, here is the code I'm trying to translate from 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();

推荐答案

我不会在Powershell中重新创建C#代码,而是以PowerShell方式进行.例如:

I wouldn't recreate the C#-code in powershell, but rather do it the PowerShell-way. Ex:

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

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

However, to answer your question, you could do it the manual way:

$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

或者您可以为其创建一个函数:

Or you could create a function for it:

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]

或者您可以编译C#代码或使用Add-Type加载已编译的dll.

Or you could compile the C# code or load an already compiled dll using Add-Type.

这篇关于PowerShell与LINQ的All()等效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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