Can I have an incrementing count variable in LINQ?
Asked Answered
P

3

62

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.

Precision answered 5/2, 2010 at 17:19 Comment(0)
A
145

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.

Albany answered 5/2, 2010 at 17:20 Comment(4)
Unfortunately, this does not (always) work with entity framework core row sets. A workaround would be to stick these rows in a List first.Heliopolis
Please explain why you strongly advise against thisDecima
@tjmoore: Because LINQ is designed for pipelines without side-effects. For example, the query I've given at the end will not do anything in itself. That just sets up the pipeline - you have to use the query in order for it to count anything... and if will count every time you iterate over query. That kind of thing can be really confusing in the real world (as opposed to trivial examples)Albany
Thanks, works, but remember, it CANNOT BE PERFORMED ON QUERYABLES, only Array, List etc. will work :)Curagh
K
8

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 };
Kareem answered 5/2, 2010 at 17:22 Comment(1)
Another answer strongly advises against this. https://mcmap.net/q/320191/-can-i-have-an-incrementing-count-variable-in-linqHipolitohipp
T
2

Just add two variable here NumberRow is for that

.Select((x,NumberRow) => new ViewModelArchiveOrder
                    {
                        NumberRow= NumberRow + 1,
                    })
Torey answered 6/5, 2019 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.