LINQ JOIN Doubt

2

Is there a right order to join? Example, I have two lists: categories and products, should I first use the from clause with the Categories or Products? And then Join? Example:

    var stockQuery = from category in categories
                     join product in products on category equals product.Category into prodGroup
                     select new { Key = category.Name, Products = prodGroup }; 

The code above works normally, but the code below does not, why?

    var stockQuery = from product in products
                     join category in categories on product.Category equals category into prodGroup
                     select new { Key = category.Name, Products = prodGroup };

Show the error that category is not in the same context, but I still do not understand why it is not ...

    
asked by anonymous 19.05.2015 / 22:39

1 answer

1

After a join, two variables are in context: the item selected in the from clause and the group created with the join clause. That is, in the following query:

from product in products
join category in categories on product.Category equals category into prodGroup
select /** TODO **/

The available variables are product and prodGroup - the product and the corresponding categories.

The variable category is not available - but it does not have to be, since it would be equal to product.Category . Here's how to resolve select

select new { Key = product.Category.Name, Products = prodGroup }; 
    
20.05.2015 / 10:08