Version 1 (modified by todd.a, 14 years ago) |
---|
The enumerable for statement is used to enumerate the elements of an object—any object that implements IEnumerable.
Grammar
enumerable-for-statement = for <variable> in <expression> <statements>
The variable can be from a pre-existing variable declaration or can be a new declaration. The expression must implement System.Collections.Generic.IEnumerable<of> or System.Collections.IEnumerable. Some of the more common objects to enumerate are lists, arrays and variable arguments.
If the variable is given an explicit type (foo as Bar), or has one due to being a pre-existing variable, then the type must be compatible with the objects being enumerated. If there is no explicit type then the type is inferred from what is being enumerated. For IEnumerable<of>, that's the type argument to the generic. For IEnumerable, the inferred type is Object.
Within the statements the variable can be assigned to.
Inside the statements, a break statement will exit the loop and a continue statement will skip the remaining statements. In either case, an if statement is used to control when the loop is broken or continued (otherwise it would be pointless to have further statements in the loop).
# Example 1 for person in people print person # Example 2 i = 1 for person in people print '[i]. [person]' i += 1 # Example 3 for line as String in lines line = line.trim if line print line # Example 4 for node in nodes if not node.isActive print 'skipping inactive node: [node]' continue print node node.process # Example 5 found = false for cust in customers if cust.name == name found = true break