多参数 linq 表达式如何初始化其参数?
在此帖子中,问题的解决方案是:
list.Where ((item,index) =>index
多参数的概念(即(item,index )
) 对我来说有点令人困惑,我不知道正确的词来缩小我的谷歌结果范围。那么 1)那叫什么?更重要的是,2)不可枚举变量如何初始化?在这种情况下,index
是如何编译为 int 并初始化为 0 的?
谢谢。
In this post the solution to the problem is:
list.Where((item, index) => index < list.Count - 1 && list[index + 1] == item)
The concept of multi-parameter (ie (item, index)
) is a bit puzzling to me and I don't know the correct word to narrow down my google results. So 1) What is that called? And more importantly, 2) How are the non-enumerable variable initialize? In this case how is index
compiled as an int and initialized to 0?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Lambda 表达式有各种语法选项:
这里的微妙之处在于
Where
有一个重载,它接受Func
,表示 值 和 index 分别(并返回匹配的bool
)。因此,Where
实现提供了索引 - 类似于:Lambda expressions have various syntax options:
The subtlety here is that
Where
has an overload that accepts aFunc<T, int, bool>
, representing the value and index respectively (and returning thebool
for the match). So it is theWhere
implementation that supplies the index - something like:使用 LINQ 时,请记住您将方法委托传递给
Where
方法。您调用的Where
的特定重载采用带有签名Func
的方法,并将为list 中的每个项目调用此方法
。在内部,这个特定的方法对每个迭代的项目进行计数,并使用该值作为第二个参数调用提供的委托:When using LINQ, remember that you are passing a method delegate to the
Where
method. The particular overload ofWhere
that you are invoking takes a method with signatureFunc<T,int,bool>
, and will call this method for each item inlist
. Internally, this particular method is keeping count for every item iterated, and calling the supplied delegate using this value as the second parameter:这个答案有点技术性......请记住,lambda 只是匿名委托(匿名方法)的语法快捷方式。
编辑:它们也可以是表达式树,具体取决于
Where
的签名(请参阅 Marc 的评论)。在功能上相当于
Where
方法具有以下签名:相当于:
这是定义项目和索引的位置。
在幕后,
Where
可能会执行类似的操作(只是猜测,您可以反编译查看):因此,这就是索引初始化并传递给您的委托(匿名、lambda 或其他)的地方。
This answer's a little more technical... Remember that lambdas are simply syntatic shortcuts to anonymous delegates (which are anonymous methods).
Edit: They can also be expression trees depending on the signature of
Where
(see Marc's comment).is functionally equivalent to
The
Where
method has the following signature:which is equivalent to:
That's where the item and index are defined.
Behind the scenes,
Where
may do something like (just a guess, you can decompile to see):So that's where index is initialized and gets passed to your delegate (anonymous, lambda, or otherwise).