The For Each Statement

The For Each statement enumerates the elements of a collection, executing the embedded statement block for each collection element.

foreach-statement:

For Each   identifier   In   expression   Do   statement-listopt   End For

Each For Each statement includes the identifier of the variable named iteration variable. During the statement execution the iteration variable represents a collection element, for which iteration is currently being executed. A compile error occurs if the embedded statement attempts to modify the iteration variable or pass the iteration variable as a reference parameter.

The expression in the statement (its type) must be a collection, and an explicit conversion must exist from the element type of the collection to the type of the iteration variable. If the expression value in the statement is Null, System.NullReferenceException is raised.

A type C is said to be a collection type if it implements the System.Collections.IEnumerable interface or implements the collection pattern by meeting all of the following criteria:

The System.Array system type is also a collection type. Since all array types derive from this type, any array type expression is permitted in the For Each statement. The order, in which array elements are traversed, is as follows. For single-dimensional arrays, elements are traversed in increasing index order from the least to the greatest. For multi-dimensional arrays, elements are traversed such that the indices of the rightmost dimension are increased first, then the next left dimension, and the leftmost dimension indices are increased last.

The For Each statement is in the following form:

For Each element In collection Do statement End For

corresponds to one of two possible expansions:

Var

enumerator: E;

element: ElementType

disposable: IDisposable;

enumerator := (collection).GetEnumerator;

Try

While enumerator.MoveNext Do

element := enumerator.Current As ElementType;

statement;

End While

Finally

disposable := enumerator as System.IDisposable;

If disposable <> Null

disposable.Dispose;

End If

End Try

Var

enumerator: IEnumerator;

element: ElementType

disposable: IDisposable;

enumerator := ((collection) As System.Collections.IEnumerable).GetEnumerator;

Try

While enumerator.MoveNext Do

element := enumerator.Current As ElementType;

statement;

End While

Finally

disposable := enumerator as System.IDisposable;

If disposable <> Null

disposable.Dispose;

End If

End Try

Example

Private Sub TestForEach();
Var
    s: Array Of string;
    s1: string;
Begin
    For Each s1 In s Do
        //Operations with s1
    End For;
End Sub;

See also:

Iteration Statements