Continue while from nested for-loop

前端 未结 2 806
遥遥无期
遥遥无期 2021-01-12 23:19

I have the following loop structure:

while ($reader.Read() -eq $true)
{
    $row = @{}
    for ($i = 0; $i -lt $reader.FieldCount; $i++)
    {
        if(som         


        
2条回答
  •  醉酒成梦
    2021-01-13 00:04

    Factoring out the inner loop to a function could improve readability, depending on how tangled up your variables are.

    function processRow($reader) {
        $row = @{}
        for ($i = 0; $i -lt $reader.FieldCount; $i++)
        {
            if(-not something...) { return $null }
            # process row
        }
        $row
    }
    
    while ($reader.Read()) {
        $row = processRow $reader
        if ($row) {
            #do more stuff...          
        }
    }
    

    But if you want to do this directly, you can, because PowerShell has labeled breaks:

    :nextRow while ($reader.Read()) {
        $row = @{}
        for ($i = 0; $i -lt $reader.FieldCount; $i++) {
            if(something...) {
                #continue with while
                continue nextRow
            }
        }
        #do more stuff...          
    }
    

提交回复
热议问题