Can I have an incrementing count variable in LINQ?
Solution 1:
Rather than using side-effects, use the overload of Select
which takes an index:
stuff.Select((value, index) => new { index, value.Name });
You could do it using side-effects, but not in the way you tried:
int counter = 0;
var query = from a in stuff
select new { count = counter++, a.Name };
I would strongly advise against this though.
Solution 2:
If you truly want it to be a counter, and not just an index, then just move the counter declaration outside the LINQ expression
var counter = 0;
from a in stuff
select new { count = counter++; a.Name };