| 1 | The '''enumerable for''' statement is used to enumerate the elements of an object—any object that implements '''IEnumerable'''. |
| 2 | === Grammar === |
| 3 | {{{ |
| 4 | enumerable-for-statement = |
| 5 | for <variable> in <expression> |
| 6 | <statements> |
| 7 | }}} |
| 8 | |
| 9 | 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. |
| 10 | |
| 11 | 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. |
| 12 | |
| 13 | Within the statements the variable can be assigned to. |
| 14 | |
| 15 | 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). |
| 16 | |
| 17 | {{{ |
| 18 | #!cobra |
| 19 | # Example 1 |
| 20 | for person in people |
| 21 | print person |
| 22 | |
| 23 | # Example 2 |
| 24 | i = 1 |
| 25 | for person in people |
| 26 | print '[i]. [person]' |
| 27 | i += 1 |
| 28 | |
| 29 | # Example 3 |
| 30 | for line as String in lines |
| 31 | line = line.trim |
| 32 | if line |
| 33 | print line |
| 34 | |
| 35 | # Example 4 |
| 36 | for node in nodes |
| 37 | if not node.isActive |
| 38 | print 'skipping inactive node: [node]' |
| 39 | continue |
| 40 | print node |
| 41 | node.process |
| 42 | |
| 43 | # Example 5 |
| 44 | found = false |
| 45 | for cust in customers |
| 46 | if cust.name == name |
| 47 | found = true |
| 48 | break |
| 49 | }}} |