如何使用Linq进行分组和SUM [英] How to use Linq to group and SUM
本文介绍了如何使用Linq进行分组和SUM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的产品类是
ProductName
类别
价格
我要显示如下信息:
Hi, I have a Product class with
ProductName
Category
Price
and I want to display an information like this:
ProductName | Category | Price
XXXVVVXXXX | Category1 | 10
XXYZXXXXXX | Category1 | 15
Total Category1: 35
YYYY | Category2 | 05
YYVV | Category2 | 10
TTTT | Category2 | 11
Total Category2: 26
Total All Categories 61
怎么可能我是用Linq做的吗?
我感谢所有建议。
我正在使用asp.net MVC 4.
How could I do this using Linq ?
I appreciate all suggestions.
I'm using asp.net MVC 4.
推荐答案
也许是某事这样吗?
Perhaps something like this?
var query =
from p in Products
group p by p.Category into g
select new { Category = g.Key, Total = g.Sum(p => p.Price), Values = g };
看到它正常工作:
http://ideone.com/ckhFNq
但是通过for循环计算总数会更有效。
See it working:
http://ideone.com/ckhFNq
But it would be more efficient just to calculate the total with a for-loop.
这篇关于如何使用Linq进行分组和SUM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文