LINQ 连接中等号的左侧和右侧有什么区别
在 Linq 中进行联接时,例如
from c incustomers join x in somelistofcustomers on x.Id equals c.Id
您将收到错误
x 不在“等于”左侧的范围内。考虑交换“等于”两侧的表达式
很简单,但我想澄清一下为什么 x 不在左侧的范围内,但不知何故在 equals 右侧的范围内
When doing a join in Linq such as
from c in customers join x in somelistofcustomers on x.Id equals c.Id
you'll get the error
x is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'
Simple enough to do, but I would like some clarification why x is not in scope on the left side, but somehow is in scope on the right side of equals
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与编译器将 LINQ 扩展为底层扩展方法的方式有关。
您的查询将被转换为:
两个 lambda 表达式
c =>; x.Id
& <代码> x => c.Id 显然其局部变量超出了范围。由于 LINQ 只是实际调用的一个很好的糖衣,因此编译器正确地抱怨该变量超出了范围。This is to do with the way that LINQ is expanded by the compiler into the underlying extension methods.
Your query is being translated into:
The two lambda expressions
c => x.Id
&x => c.Id
clearly have their local variables out of scope. Since LINQ is just a nice sugar coating over the actual calls the compiler correcly complains that the variable is out of scope.这只是一个约定,基本上连接的结构如下
identifier
和{outer-key-selector}
是配对的,identifier2
也是配对的> 和{inner-key-selector}
- 您无法切换顺序,因为它们的位置在连接语法中是固定的。It's just a convention, basically the structure of a join is as follows
identifier
and{outer-key-selector}
are paired, and so areidentifier2
and{inner-key-selector}
- you can't switch the order, because their position is fixed in the join syntax.