For Each...Next Statement


For Each...Next Statement

Syntax

     For Each element [As datatype] In group        [statements]        [Exit For]        [statements]        [Continue For]        [statements]     Next [element] 


element (required; any)

An object variable to which the current element from the group is assigned. Its data type must be compatible with the data elements in group.


datatype (optional)

New in 2003. The data type of element when including the declaration in the For Each clause.


group (required; IEnumerable interface)

A collection or array of elements to iterate. The object must implement the System.Collections.IEnumerable interface.


statements (optional)

Lines of program code to execute within the loop.

Description

Defines a loop that iterates through all items in a collection or array. element and group must be of compatible data types. The code within the loop is executed once for each element in group, with element being assigned to each successive element within group, one assignment per pass. The Exit For statement can be used at any time to exit the loop immediately.

New in 2005. The Continue For statement can be used at any time to immediately jump back to the top of the loop and attempt to process the next iteration. The element variable is assigned the next element in group upon reaching the top of the loop.

Usage at a Glance

  • The For Each...Next code block is executed only if group contains at least one element. If group is an empty collection or an array that has not yet been initialized, an error occurs.

  • All statements are executed for each element in group in turn, until either there are no more elements in group or the loop is exited prematurely using the Exit For statement. Program execution then continues with the line of code following Next.

  • For Each...Next loops can be nested, but each element must be unique, as in:

         For Each groupScan In bigCollectionOfItems        For Each subScan In groupScan.DetailItems           ...processing code goes here...        Next subScan     Next groupScan 

Version Differences

  • In VB 6, element had to be a variable of type Variant. .NET removes this restriction; element can be a strongly typed data type or the more generic System.Object type.

  • Visual Basic .NET 2003 adds the As clause to the For Each statement for inline counter declaration.

  • Visual Basic 2005 includes the Continue For statement.

See Also

For...Next Statement




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net