What is the Linq.First equivalent in PowerShell?

后端 未结 4 1042
孤城傲影
孤城傲影 2021-02-01 12:44

The snippet below detects from a list of files which of them is a Directory on Ftp

as C# it will be like below

var files = new List(){\"App         


        
4条回答
  •  無奈伤痛
    2021-02-01 13:34

    Something like this...

    $files = @("App_Data", "bin", "Content")
    $line = "drwxr-xr-x 1 ftp ftp              0 Mar 18 22:41 App_Data"
    $dir = $files | Where { $line.EndsWith($_) } | Select -First 1
    

    These versions of the last line would all accomplish the same:

    $dir = @($files | Where { $line.EndsWith($_) })[0]
    
    $dir = $files | Where { $line.EndsWith($_) } | Select -index 0
    
    $dir = $files | Where { $line.EndsWith($_) } | Select -First 1
    

    It was pointed out that the above is not exactly equivalent in behavior to Linq.First because Linq.First throws exceptions in two cases:

    • Throws ArgumentNullException when source or predicate is null.
    • Throws InvalidOperationException when source sequence is empty or no element satisfies the condition in predicate.

    If you wanted that behavior exactly, you'd need some extra guard code.

提交回复
热议问题