Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq 'into' keyword confusion

Tags:

I was looking at a co-workers Linq query, shown below (the query executes correctly):

from ea in EquipmentApplication join erl in EquipmentRoutingLocation on ea.EquipmentID equals erl.EquipmentID into erlWithNulls  from erlAll in erlWithNulls.DefaultIfEmpty() join rl in RoutingLocation on erlAll.RoutingLocationID equals rl.RoutingLocationID into rlWithNulls  from rlAll in rlWithNulls.DefaultIfEmpty() where ea.Equipment.Master_Cell.Area.Unit.UnitID == 1160 select new { ea.Equipment, ea.ApplicationFriendlyName, rlAll } 

I'm confused as to why this works. My understanding (perhaps incorrectly) is that the 'into' keyword ends the current scope/context (and any variables created are now out of scope) and creates a new one. If this is true, why is the 'ea' variable still in scope in the last part of the query?

like image 307
Randy Minder Avatar asked Oct 04 '10 13:10

Randy Minder


2 Answers

When used with the select keyword, into will end the scope.
When used with the join keyword, into will add a variable containing all of the matching items from the join. (This is called a Group Join)

like image 103
SLaks Avatar answered Oct 04 '22 02:10

SLaks


"into" has two different meanings:

  • In a join clause, it changes the translation from using Join to GroupJoin. This means that instead of getting one result per matching pair, you get one result for each element of the original sequence, and that result contains the key and all the results from the other sequence, as a group. See Enumerable.GroupJoin for more details
  • In a select or group...by it becomes a query continuation, effectively starting a new query with the results of the old one in a new range variable.
like image 20
Jon Skeet Avatar answered Oct 04 '22 02:10

Jon Skeet