vb.net - 中断/退出嵌套在 vb.net 中

标签 vb.net for-loop nested-loops

如何退出 vb.net 中的嵌套 for 或循环?

我尝试使用 exit for 但它只跳转或中断了一个 for 循环。

我怎样才能做到以下几点:

for each item in itemList
     for each item1 in itemList1
          if item1.text = "bla bla bla" then
                exit for
          end if
     end for
end for

最佳答案

不幸的是,没有 exit 两级 for 语句,但是有一些解决方法可以完成您想要的操作:

  • 转到。一般来说,使用gotoconsidered to be bad practice (这是正确的),但是仅使用 goto 向前跳转出结构化控制语句通常被认为是可以的,特别是如果替代方案是拥有更复杂的代码。

    For Each item In itemList
        For Each item1 In itemList1
            If item1.Text = "bla bla bla" Then
                Goto end_of_for
            End If
        Next
    Next
    
    end_of_for:
    
  • 虚拟外部 block

    Do
        For Each item In itemList
            For Each item1 In itemList1
                If item1.Text = "bla bla bla" Then
                    Exit Do
                End If
            Next
        Next
    Loop While False
    

    Try
        For Each item In itemlist
            For Each item1 In itemlist1
                If item1 = "bla bla bla" Then
                    Exit Try
                End If
            Next
        Next
    Finally
    End Try
    
  • 单独函数:将循环放入单独的函数中,可以通过return退出。不过,这可能需要您传递大量参数,具体取决于您在循环内使用的局部变量数量。另一种方法是将 block 放入多行 lambda 中,因为这将在局部变量上创建一个闭包。

  • bool 变量:这可能会降低您的代码的可读性,具体取决于您有多少层嵌套循环:

    Dim done = False
    
    For Each item In itemList
        For Each item1 In itemList1
            If item1.Text = "bla bla bla" Then
                done = True
                Exit For
            End If
        Next
        If done Then Exit For
    Next
    

关于vb.net - 中断/退出嵌套在 vb.net 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5312291/

相关文章:

.net - VB.NET函数以字符串形式获取属性名称

vb.net - 使用 OpenDoc6 打开工程图文档

asp.net - 当我单击其中一个更新面板中的按钮时,如何防止所有更新面板重新加载?

r - nlm起始值的选择问题

java - ElementNotVisibleException 错误

excel - 从 Excel 中删除不需要的字符(Visual Basic)

c++ - 如何退出(转到父循环的下一个元素)for 循环内的 for 循环

python - 嵌套 for 循环搜索 2 个列表

python - 嵌套循环属性错误: __exit__ (Selenium script) when opening file

Bash 退出不退出