Continue while from nested for-loop

2020-04-08 00:56发布

I have the following loop structure:

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

Now, is there any way to continue from within the for loop with the next iteration of the outer while loop without any break-variable? So if "something is true" I do not want to go #do more stuff but instead do the next $reader.read(). Continue only goes to the next iteration of the for loop. Break will only break the for loop.

2条回答
成全新的幸福
2楼-- · 2020-04-08 01:36

EDIT: a revised, recursive (and untested!) solution so your millage may vary:

function doReader()
{
    while ($reader.Read() -eq $true)
    {
        $row = @{}
        for ($i = 0; $i -lt $reader.FieldCount; $i++)
        {
            if(something...)
            {
                #continue with while
                doReader
                break;
            }
        }
    }
}
doReader
#do more stuff
查看更多
对你真心纯属浪费
3楼-- · 2020-04-08 01:40

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...          
}
查看更多
登录 后发表回答