C# 带有 GROUP 和 SUM 的 LINQ 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12251413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ Query with GROUP and SUM
提问by Luke
Please help me to get my head around querying using LINQ with a GROUP and SUM.
请帮助我了解如何使用带有 GROUP 和 SUM 的 LINQ 进行查询。
// Query the database
IEnumerable<BestSeller> best_sellers = from bs in (db.MYDATABASE).Take(25)
where bs.COMPANY == "MY COMPANY"
group bs by bs.PRODCODE into g
orderby g.Sum(g.MQTY)
select new BestSeller()
{
product_code = ,
product_description = ,
total_quantity =
};
I wish to:
我希望:
- Take the top 25 items from db.MYDATABASE
- Group all the results by bs.PRODCODE
- Order it by the sum total for each bs.PRODCODE
- Where the company is "MY COMPANY"
- Then pipe the data in to my
BestSeller()objects
- 从 db.MYDATABASE 中取出前 25 项
- 按 bs.PRODCODE 对所有结果进行分组
- 按每个 bs.PRODCODE 的总和排序
- 公司所在位置为“我的公司”
- 然后将数据通过管道传输到我的
BestSeller()对象
I'm confused, because as soon as I add my groupin to the mix, my bsvariable becomes useless.
我很困惑,因为一旦我将group我的bs变量添加到组合中,我的变量就变得无用了。
采纳答案by Jon Skeet
I'm confused, because as soon as I add my group in to the mix, my bs variable becomes useless.
我很困惑,因为一旦我将我的组添加到组合中,我的 bs 变量就变得无用了。
Yes, because you no longer have a single item - you're now processing a sequence of groupsof items. You can get at first item for each group, which I assume would be a valid way of getting at the description?
是的,因为您不再拥有单个项目 - 您现在正在处理一系列项目组。您可以获得每个组的第一个项目,我认为这是获取描述的有效方式?
var query = from bs in db.MYDATABASE.Take(25)
where bs.COMPANY == "MY COMPANY"
group bs by bs.PRODCODE into g
orderby g.Sum(x => x.MQTY)
select new BestSeller
{
product_code = g.Key,
product_description = g.First().DESCRIPTION,
total_quantity = g.Sum(x => x.MQTY)
};
Note that without specifying an ordering, "the top 25 items from db.MYDATABASE" makes no sense. "Top" in what way? You may well want:
请注意,如果不指定排序,“db.MYDATABASE 中的前 25 个项目”是没有意义的。“顶”在什么地方?你可能想要:
from bs in db.MYDATABASE.OrderByDescending(x => x.Price).Take(25)
or something similar. Note that if none of those have a company of "MY COMPANY" you'll end up with no results...
或类似的东西。请注意,如果这些人都没有“我的公司”的公司,您最终将没有结果......
Or if you want the top 25 bestsellers, you want the "take" part at the very end:
或者,如果您想要排名前 25 的畅销书,那么您希望在最后的部分是“take”部分:
var query = from bs in db.MYDATABASE
where bs.COMPANY == "MY COMPANY"
group bs by bs.PRODCODE into g
orderby g.Sum(x => x.MQTY) descending
select new BestSeller
{
product_code = g.Key,
product_description = g.First().DESCRIPTION,
total_quantity = g.Sum(x => x.MQTY)
};
var top25 = query.Take(25);

