So I have this example of a LINQ Query:
var productsPerSupplier = from s in suppliers
join p in products
on s.Id equals p.SupplierId
into sp
select new
{
SupplierId = s.Id,
SupplierName = s.Name,
ProductCount = sp.Count()
};
How does the count function know to count the number of products for each supplier? What is the structure of sp table? Isn't it supposed to count all the rows in the table?
CodePudding user response:
See here in the docs. into
keyword creates hierarchical grouping in the results where each item in the left table is associated with one or more items in the right table of your join
. This is why it knows how to perform Count()
on individual groups.
CodePudding user response:
Try following :
var productsPerSupplier = (from s in suppliers
join p in products
on s.Id equals p.SupplierId
select new {s = s, p = p}
).GroupBy(x => x.s.ID)
.Select(x => new
{
SupplierId = x.Key,
SupplierName = x.s.First().Name,
ProductCount = x.Count()
}).ToList();