tags:

views:

45

answers:

2

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?

+4  A: 

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)

SLaks
+4  A: 

"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.
Jon Skeet