我可以使用什么Linq查询来按类别返回所有产品的计数? [英] What Linq query can I use to return a count of all products by Category?
问题描述
给出以下表格结构,如何使用Linq查询返回类别名称列表和该类别中产品的总数?
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
我的理想回报是:
Clothes 156
Electronics 2149
Utensils 412
等等.
感谢您的有用建议,我现在有这个建议:
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.
推荐答案
from c in Category
join p in Product on c.ID equals p.IDCategory
group p by c.Name into g
select new
{
Name = g.Key,
Count = g.Count()
}
这将适用于任何LINQ风格,并按名称而不是类别ID进行分组.
That will work in any flavor of LINQ, and groups by the Name, rather than the ID of category.
如果您使用的是LINQ to Entities,这可能会更快,并且使用ID而不是名称进行分组:
If you are using LINQ to Entities, this may be faster, and groups on ID rather than name:
from p in Product
group p by p.Category into g
select new
{
Name = g.Key.Name,
Count = g.Count()
}
这篇关于我可以使用什么Linq查询来按类别返回所有产品的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!