For Each Statement
Runs a sequence of statements for each item in a data structure.
Syntax
For Each element [ As type ] In group
[ statements ]
End [ For ]
Parts
element- Mandatory variable name declaration.
type- Usually optional data type of
element. - Mandatory if
groupis an array literal between braces ({ }) andelementis without a type character. group- Mandatory collection object, string expression, or array literal.
statements- Optional One or more statements between the lines that start with
For EachandEnd. These run one time for each item in a collection. - The alternative is two or more groups of statements.
The initial group starts with
Exit When, and runs the same as given above. The subsequent groups start withWhen, and run when (1) the loop cannot start, or (2) after the loop stops. See § When statements for more information. End- Completes the statement.
You can also use
End For. - You can change the syntax of this part. See @Option Directive for more information.
Instructions
End For is not the same as Exit For.
Use the construct For Each when you must run one or more statements again and again.
It is recommended when you must run statements for each item in a collection.
Other loop constructs are possibly more flexible.
See the See also section below for more information.
Usual operation
TODO
Loop-index counter
With loops of this type, you can use a magic integer constant %INDEX.
It starts at zero (0) and increases by one (1) with each iteration.
If you nest loops of this type, %INDEX can refer to a different loop to what you think.
Thus, we recommend that you make special counter variables as an alternative, if necessary.
Exit For
The statement Exit For can stop this type of loop.
Exit For immediately runs the statement after End.
Exit can also stop more than one nested loop.
You can use the statement «Exit For, For» in the inner loop to stop two loops.
When statements
To find if a loop of this type completed because it went through all of the items, use When DONE.
To find if a loop of this type did not run because group is null or empty, use When NONE.
See Exit When Clause for more information.
Examples
Elements in an array literal
For Each day As String In { "Mon", "Tue", "Wed", "Thu", "Fri" }
' do something
End For
Characters in a string
Var s = "ViviFire"
For Each c As Char In s
' do something
End For
See also
- Doo...Loop Statement – runs code given a pre-condition or a post-condition.
- For Statement – Runs through a range of values.
- While Statement – Runs code given a pre-condition.
- Yield Statement
- @Iterator
- Iterators
- Exit Statement
- Exit When Clause
- Loop Constructs
- @Option Directive