For Loop Expressions

For Loop Expressions are a way to use a regular for Loop as part of an expression, symmetrical to the new Case Expressions and If Expressions. The result of the for loop expression is, in essence, an Iterator and can be treated as a Sequence.

For/to loop

For loop expressions are a simple way to use the Pascal for i := start to end syntax to create a sequence. All features supported by the Oxygene for loops are supported by the loop expression except that do is replaced with yield (as in regular method-based Iterators:

var lList := for i := 0 to 10 step 2 yield i*i; // returns 0, 4, 16, 36, 64, 100

For each loop

Similarly, the for each loop syntax can also be used:

var lOriginalList: array of Integer := [0,1,2,3,4,5,6,7,8,9];

//...

var lList := for each el in lOriginalList index n yield el * n; // returns: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81

Details

The result of a For Loop Expression is a Sequence of the type of the yield expression. Items are not pre-evaluated, but will be looped through whenever the sequence is later enumerated (for example via another for each loop). Note again that the type of both loops is determined by the result type of the yield expression, which can be any type.

Since the result of a 'For Loop Expression is a sequence of Expressions, it is only natural that the loop body must consist of a single expression (in contrast to regular For Loops, where any statement or even a block of statements can be executed as part of the loop).

For example:

var lList := for i := 0 to 10 step 2 yield (i*i).ToString;
// lList now is a sequence of string; '0', '4', '16', '36', '64', '100'