请帮助我了解使用带有 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 =
};
我希望:
- 从 db.MYDATABASE 中取出前 25 项
- 按 bs.PRODCODE 对所有结果进行分组
- 按每个 bs.PRODCODE 的总和排序
- 公司是“我的公司”
- 然后将数据通过管道传输到我的
BestSeller()
对象
我很困惑,因为一旦我将我的 group
添加到混合中,我的 bs
变量就变得无用了。
最佳答案
I'm confused, because as soon as I add my group in to the mix, my bs variable becomes useless.
是的,因为您不再有单个项目 - 您现在正在处理一系列组项目。您可以首先获取每个组的第一个项目,我认为这是获取描述的有效方式?
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)
};
请注意,如果不指定顺序,“来自 db.MYDATABASE 的前 25 项”是没有意义的。 “顶”在什么方面?你可能想要:
from bs in db.MYDATABASE.OrderByDescending(x => x.Price).Take(25)
或类似的东西。请注意,如果这些人都没有“我的公司”的公司,那么您最终将没有任何结果...
或者,如果您想要排名前 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);
关于c# - 使用 GROUP 和 SUM 的 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12251413/