Doubt about JOIN of LINQ

Asked

Viewed 111 times

2

Is there a right order to use Join? For example, I have two lists: Categories and products, should I first use the from clause with Categories or Products? And then in 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 };

Shows the error that category it’s not in the same context, but I still don’t understand why he’s not...

1 answer

1


After performing a Join, two variables are in context: the item selected in the clause from and the group established under join. 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 does not need to be, as it would equal product.Category. This is how to solve the select

select new { Key = product.Category.Name, Products = prodGroup }; 
  • In addition: it would be possible to access the Join’s Category variable if the into clause did not need to be used. This clause hides the variables used to compose its result.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.