Continue while from nested for-loop

前端 未结 2 782
遥遥无期
遥遥无期 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...          
    }
    
    0 讨论(0)
  • 2021-01-13 00:11

    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
    
    0 讨论(0)
提交回复
热议问题