VB.NET For Loop Examples (For Each) - Dot Net Perls
Có thể bạn quan tâm
Again and again, a VB.NET loop executes statements. The For-loop proceeds from a lower to an upper bound—a step indicates its progression.
Another loop, For-Each, requires a collection—it enumerates each item. Other loops, such as While, continue until a condition is met. If the end is not yet known, While is best.
Simple example
To begin, we see a simple For-loop that starts at 0, and continues to 2 (it includes 2, which is specified as the loop bound). In VB.NET the top bound is inclusive.
Complex example
Consider a For-loop that goes from 0 to (and including) 5. We can optionally place an Exit For inside this loop for added control over iteration.
Step 1 We use the lower bound 0 and the upper bound 5 in this For-loop statement. The two bounds are inclusive (0 and 5 are included).Step 2 We print the current index of the For loop on each iteration. We exit after 3 is printed.Step 3 We see the Exit For statement—this statement breaks out of the enclosing For-loop. Exit works in all loops and Subs.Step
Here we want to decrement the counter variable instead of increment it. In other words, we go down not up. We start at 10 and then continued own in steps of 2 to 0.
Also The Step keyword is used near the end of the For-statement. A step is the delta each loop iteration will have.So If you want to decrement by 1 each time, you can use -1. If you want to increment by 1, use 1.Nested For
In many programs, nested loops are essential. In a For-loop, we uniquely name the iteration variable. And we reference all iteration variables (row, column) in an inner block.
Module Module1 Sub Main() ' Use a nested For-loop. For row As Integer = 0 To 2 For column As Integer = 0 To 2 Console.WriteLine("{0},{1}", row, column) Next Next End Sub End Module0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2For Each example
Next, we consider the For-Each loop construct. We create a String array (of color names). We enumerate each string in the array.
Tip By using For-Each, we reduce errors in programs. We do not need to maintain the index ourselves.Here We have a "color" variable we can access in each iteration of the loop. We just pass it to Console.WriteLine.Module Module1 Sub Main() ' The input array. Dim colors() As String = {"blue", "orange", "yellow", "magenta"} ' Loop over each element with For Each. For Each color As String In colors Console.WriteLine(color) Next End Sub End Moduleblue orange yellow magentaFor Each, compared
How does the For-Each loop compare to the For-loop? First, the For-loop construct may be faster in some cases.
However As we see in this example, the For-loop has more complexity and is longer in the source code.Tip To use For, you need to declare an iteration variable and also specify the loop bounds.Module Module1 Sub Main() ' The input array. Dim shapes() As String = {"circle", "square", "ellipse", "rectangle"} ' Loop over each element with For Each. For Each shape As String In shapes Console.WriteLine(shape) Next ' Blank line. Console.WriteLine() ' Use For-loop. For index As Integer = 0 To shapes.Length - 1 Console.WriteLine(shapes(index)) Next End Sub End Modulecircle square ellipse rectangle circle square ellipse rectangleFor Each, List
Often we use For Each on a List. The loop works on anything that implements IEnumerable, which includes Lists and arrays. Here we enumerate an Integer List.
Module Module1 Sub Main() ' Create new List of 5 Integers. Dim ids = New List(Of Integer)({100, 101, 120, 121, 123}) ' Enumerate all IDs. For Each id In ids Console.WriteLine($"FOR EACH, CURRENT ID = {id}") Next End Sub End ModuleFOR EACH, CURRENT ID = 100 FOR EACH, CURRENT ID = 101 FOR EACH, CURRENT ID = 120 FOR EACH, CURRENT ID = 121 FOR EACH, CURRENT ID = 123For, String Chars
The For and For-Each loops can be used on String variables. This gives us a way to check, or process, each character in the Object data.
Detail The For-Each loop can also be used on Strings. When you do not need the index, For-Each is a better, cleaner choice.Module Module1 Sub Main() Dim value As String = "cat" ' Start at zero and proceed until final index. For i As Integer = 0 To value.Length - 1 ' Get character from string. Dim c As Char = value(i) ' Test and display character. If c = "c" Then Console.WriteLine("***C***") Else Console.WriteLine(c) End If Next End Sub End Module***C*** a tAdjacent indexes
Often in For-loops, we need adjacent indexes. We can start at the second index (1) and then access the previous element each time, getting all pairs.
Tip With this For-loop, we could check for duplicates in a sorted array, or repeated values in any array.Module Module1 Sub Main() Dim value As String = "abcd" ' Start at one so the previous index is always valid. For i As Integer = 1 To value.Length - 1 ' Get adjacent characters. Dim c As Char = value(i - 1) Dim c2 As Char = value(i) Console.WriteLine(c & c2) Next End Sub End Moduleab bc cdLong, non-integer indexes
The For-loop supports non-integer indexes like Long, Short and UShort. Char is not supported. Here we use For with a Long index.
Module Module1 Sub Main() ' Loop over last three Longs. For d As Long = Long.MaxValue To Long.MaxValue - 2 Step -1 Console.WriteLine(d) Next End Sub End Module9223372036854775807 9223372036854775806 9223372036854775805Nested For, Exit For
Let us revisit nested "For" loops with a more complex example. Here we have a loop that decrements inside a loop that increments.
Part 1 We iterate from 0 to 3 inclusive in the outer For-loop. Inside this loop, we have a nested loop.Part 2 This is a decrementing loop—we specify its Step as -1, so it counts down.Part 3 We try to exit the inner loop. When 2 for-loops are nested, and we have an Exit For statement, the inner loop is exited.Module Module1 Sub Main() ' Part 1: outer for-loop. For value As Integer = 0 To 3 Console.WriteLine("OUTER LOOP: {0}", value) ' Part 2: inner for-loop. For value2 As Integer = 5 To 0 Step -1 Console.WriteLine("INNER LOOP: {0}", value2) ' Part 3: exit condition. If value2 = 3 Then ' ... Exit the inner loop. Console.WriteLine("EXIT INNER FOR") Exit For End If Next Next End Sub End ModuleOUTER LOOP: 0 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR OUTER LOOP: 1 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR OUTER LOOP: 2 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR OUTER LOOP: 3 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FORThe For-loop is a core looping construct. It provides a way to explicitly specify the loop bounds. Meanwhile, For Each helps us avoid coding errors by not using the index at all.
Từ khóa » Visual Basic For Next
-
For...Next Statement - Visual Basic - Microsoft Docs
-
For Each...Next Statement - Visual Basic - Microsoft Docs
-
VB.Net - For...Next Loop - Tutorialspoint
-
VB.NET For Next Loop - Javatpoint
-
Visual Basic For Next Statemen | The Coding Guys
-
For Next Loop - VB.NET - RIP Tutorial
-
Visual Basic Tutorial - 26 - For Next Loop - YouTube
-
For Loop - For...Next Statement - VB.NET
-
Visual Basic (VB) For Loop - Tutlane
-
Looping In Visual Basic 2010
-
Visual Basic/Loops - Wikibooks, Open Books For An Open World
-
For...Next Statement
-
Visual Basic For Loops - Techotopia
-
For-Next Loop Visual Basic - Vba - Stack Overflow