Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linq

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

like image 226
Ralph Shillington Avatar asked Mar 07 '11 00:03

Ralph Shillington


2 Answers

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.

like image 135
Enigmativity Avatar answered Nov 15 '22 01:11

Enigmativity


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.

like image 44
BrokenGlass Avatar answered Nov 15 '22 02:11

BrokenGlass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!