PowerShell equivalent of LINQ Any()?

前端 未结 11 682
灰色年华
灰色年华 2020-12-01 03:29

I would like to find all directories at the top level from the location of the script that are stored in subversion.

In C# it would be something like this

         


        
11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 04:05

    I think that the best answer here is the function proposed by @JaredPar, but if you like one-liners as I do I'd like to propose following Any one-liner:

    # Any item is greater than 5
    $result = $arr | %{ $match = $false }{ $match = $match -or $_ -gt 5 }{ $match }
    

    %{ $match = $false }{ $match = $match -or YOUR_CONDITION }{ $match } checks that at least one item match condition.

    One note - usually the Any operation evaluates the array until it finds the first item matching the condition. But this code evaluates all items.

    Just to mention, you can easily adjust it to become All one-liner:

    # All items are greater than zero
    $result = $arr | %{ $match = $false }{ $match = $match -and $_ -gt 0 }{ $match }
    

    %{ $match = $false }{ $match = $match -and YOUR_CONDITION }{ $match } checks that all items match condition.

    Notice, that to check Any you need -or and to check All you need -and.

提交回复
热议问题