Can I have an incrementing count variable in LINQ?

LinqLinqpad

Linq Problem Overview


I want to do something like this:

from a in stuff
let counter = 0
select new { count = counter++, a.Name };

But I get a error telling me that counter is read only. Is there a way to do something similar to this, without declaring a variable outside of the query?

Basically, I just want to show a count/index column in LINQPad (which is awesome, BTW), which means I can't declare counter ahead of time.

Linq Solutions


Solution 1 - Linq

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 - Linq

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 };

Solution 3 - Linq

Just add two variable here NumberRow is for that

.Select((x,NumberRow) => new ViewModelArchiveOrder
                    {
                        NumberRow= NumberRow + 1,
                    })

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike PaterasView Question on Stackoverflow
Solution 1 - LinqJon SkeetView Answer on Stackoverflow
Solution 2 - LinqJaredParView Answer on Stackoverflow
Solution 3 - Linqsaeed bagheriView Answer on Stackoverflow