VB.NET的结合For Each..Next和Do..While

时间:2011-03-21 15:18:14

标签: asp.net vb.net loops foreach while-loop

我有一个像这样的数组:

Dim classes() as String = {"FR%", "SO", "JR", "SR", "SR5"}

我需要像这样循环遍历这些值:

For Each value as String in classes

Next

问题是,我在For Each..Next里面有一个If..Then..Else子句,它说的是:

If actual_class = value Then
  txt.Text = "Welcome"
Else
  txt.Text = "Goodbye"

当我运行它时,除非个体是字符串数组中的最后一个值(“SR5”),否则它们将获得消息“Goodbye”...所以,我需要以某种方式迭代遍历每个值,就像是完成For Each..Next循环,但是一旦它击中学生的类就会突破循环,就像Do..While循环一样 - 这样它们的值就不会被Else子句超越。

2 个答案:

答案 0 :(得分:8)

如果您想要摆脱循环,请执行Exit For

请参阅For EachExit

更新了示例

txt.Text = "Goodbye"

For Each value as String in classes
    If actual_class = value Then
        txt.Text = "Welcome"
        Exit For
    End If
Next

答案 1 :(得分:0)

txt.Text = ""

For Each value as String in classes
    If actual_class = value Then
        txt.Text = "Welcome"
    Else
        txt.Text = "Goodbye"
    End If
Next