Is it possible to write the following \'foreach\' as a LINQ statement, and I guess the more general question can any for loop be replaced by a LINQ statement.
I\'m not i
In general yes, but there are specific cases that are extremely difficult. For instance, the following code in the general case does not port to a LINQ expression without a good deal of hacking.
var list = new List<Func<int>>();
foreach ( var cur in (new int[] {1,2,3})) {
list.Add(() => cur);
}
The reason why is that with a for loop, it's possible to see the side effects of how the iteration variable is captured in a closure. LINQ expressions hide the lifetime semantics of the iteration variable and prevent you from seeing side effects of capturing it's value.
Note. The above code is not equivalent to the following LINQ expression.
var list = Enumerable.Range(1,3).Select(x => () => x).ToList();
The foreach sample produces a list of Func<int>
objects which all return 3. The LINQ version produces a list of Func<int>
which return 1,2 and 3 respectively. This is what makes this style of capture difficult to port.