Given the following table structure, how can I use a Linq query to return a list of Category names and the total count of products in that category?
Category
---------
ID
Name
Product
---------
ID
IDCategory
Name
My ideal, return would be:
Clothes 156
Electronics 2149
Utensils 412
Etc.
EDIT:
Thanks for the helpful suggestions, I now have this:
class Program
{
static void Main(string[] args)
{
MyDatabaseEntities entities = new MyDatabaseEntities();
var result = from c in entities.Categories
join p in entities.Products on c.ID equals p.IDCategory
group p by c.Name into g
select new
{
Name = g.Key,
Count = g.Count()
};
Console.WriteLine(result.ToString());
Console.ReadLine();
}
}
How exactly can I output what is in the result? During debugging I can view the variables values and it has what I need I just don’t know how to show it.
That will work in any flavor of LINQ, and groups by the Name, rather than the ID of category.
If you are using LINQ to Entities, this may be faster, and groups on ID rather than name: