First off, you are correct to be concerned about the first version. Each delegate created by that lambda is closed over the same variable and therefore as that variable changes, the meaning of the query changes.
Second, FYI we are highly likely to fix this in the next version of C#; this is a major pain point for developers.
(UPDATE: This answer was written in 2011. We did in fact take the fix described below in C# 5.)
In the next version each time you run through the "foreach" loop we will generate a new loop variable rather than closing over the same variable every time. This is a "breaking" change but in the vast majority of cases the "break" will be fixing rather than causing bugs.
The "for" loop will not be changed.
See http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/ for details.
Third, there is no problem with the query comprehension version because there is no closed-over variable that is being modified. The query comprehension form is the same as if you'd said:
return dt.Rows.Select(dr=>GetStringFuncOutput(dr.ToString));
The lambda is not closed over any outer variable, so there is no variable to be modified accidentally.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…