Hi I have a SQL statement which joins a Category and Product table. It returns the CategoryID and the number of products in that category.
Select Category.CategoryID,
COUNT(Product.ProductID) AS NumberProducts
From Category Inner Join Product on Category.CategoryID = Product.CategoryID
GROUP BY Category.CategoryID
I'm trying to write a LINQ query to do the same. What should I Group By and where do I call the Count function in LINQ query?
var prodCounts =
from cat in ctx.Categories
join prod in ctx.Products
on cat.CategoryID equals prod.CategoryID
group cat by cat.CategoryID into catGp
select
new
{
CategoryID = catGp.Key,
NumberProducts = catGp.Count()
};
odubhgaill2
Member
42 Points
83 Posts
LINQ - using Group By and Count
Nov 03, 2008 10:26 AM|LINK
Hi I have a SQL statement which joins a Category and Product table. It returns the CategoryID and the number of products in that category.
Select Category.CategoryID,
COUNT(Product.ProductID) AS NumberProducts
From Category Inner Join Product on Category.CategoryID = Product.CategoryID
GROUP BY Category.CategoryID
I'm trying to write a LINQ query to do the same. What should I Group By and where do I call the Count function in LINQ query?
thanks
JMayo
Contributor
2458 Points
311 Posts
MVP
Re: LINQ - using Group By and Count
Nov 03, 2008 06:33 PM|LINK
Hi,
How about this:
var prodCounts = from cat in ctx.Categories join prod in ctx.Products on cat.CategoryID equals prod.CategoryID group cat by cat.CategoryID into catGp select new { CategoryID = catGp.Key, NumberProducts = catGp.Count() };JoeAuthor of Microsoft Visual Studio 2010: A Beginner's Guide/McGraw-Hill
Free C# Tutorial