我可以在 LINQ 中使用递增计数变量吗?
我想做这样的事情:
from a in stuff
let counter = 0
select new { count = counter++, a.Name };
但我收到一条错误消息,告诉我计数器是只读的。有没有办法做类似的事情,而无需在查询之外声明变量?
基本上,我只想在 LINQPad 中显示计数/索引列(顺便说一句,这很棒),这意味着我不能提前申报柜台。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要使用副作用,而是使用带有索引的
Select
重载:您可以使用副作用来做到这一点,但不是以您尝试的方式:
我会但强烈建议不要这样做。
Rather than using side-effects, use the overload of
Select
which takes an index:You could do it using side-effects, but not in the way you tried:
I would strongly advise against this though.
如果您确实希望它是一个计数器,而不仅仅是一个索引,那么只需将计数器声明移到 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
只需在此处添加两个变量
NumberRow
即可Just add two variable here
NumberRow
is for that