Can I have an incrementing count variable in LINQ?

后端 未结 3 1048
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 23:57

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 c

相关标签:
3条回答
  • 2021-02-05 00:06

    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.

    0 讨论(0)
  • 2021-02-05 00:11

    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 };
    
    0 讨论(0)
  • 2021-02-05 00:27

    Just add two variable here NumberRow is for that

    .Select((x,NumberRow) => new ViewModelArchiveOrder
                        {
                            NumberRow= NumberRow + 1,
                        })
    
    0 讨论(0)
提交回复
热议问题