开发者

What's the difference between left side and right side of the equals in a LINQ join

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


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:

customers.Join(somelistofcustomers, c => x.Id, x => c.Id, (c, x) => ...)

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.


It's just a convention, basically the structure of a join is as follows

from identifier in {outer-sequence} 
join identifier2 in {inner-sequence} 
on {outer-key-selector} equals {inner-key-selector}

identifier and {outer-key-selector} are paired, and so are identifier2 and {inner-key-selector} - you can't switch the order, because their position is fixed in the join syntax.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜