本文介绍了我可以在LINQ中增加计数变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

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?

基本上,我只想在 LINQPad 中显示一个计数/索引列(太棒了,顺便说一句) ,这意味着我无法提前声明计数器.

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.

推荐答案

不是使用副作用,而是使用Select的重载,该重载需要一个索引:

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.

这篇关于我可以在LINQ中增加计数变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 00:26