我见过几十篇与此类似的帖子,但我无法让它发挥作用。
使用asp.net MVC框架,我有一个名为Contributions的表,其中包含“ContributionDate”列和“Amount”列。我正在加载要在图表中显示的日期和金额:
var results = db.Contributions.Where(c => c.Amount > 0);
ArrayList xValue = new ArrayList();
ArrayList yValue = new ArrayList();
results.ToList().ForEach(c => xValue.Add(c.ContributionDate));
results.ToList().ForEach(c => yValue.Add(c.Amount));
以上作品。现在我想总计(即总计)每年的金额。我见过类似下面的例子,但我显然很无能(在这个例子中,编译器不喜欢新的{}语句中的“c.ContributionDate”):
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate )
.Select(c => new {Amount = c.Sum(b => b.Amount), Date=c.ContributionDate});
感谢您的帮助!
答案 0 :(得分:3)
当您执行GroupBy
时,您对元素进行分组的键由Key
属性表示。
试试这个:
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate )
.Select(c => new { Amount = c.Sum(b => b.Amount), Date = c.Key });
但是这会按整个ContributionDate
值对项目进行分组,而不仅仅是按年份。要做到这一点,你必须做这样的事情:
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate.Year)
.Select(c => new
{
Amount = c.Sum(b => b.Amount),
Date = new DateTime(c.Key, 1, 1)
});
但由于这似乎是实体框架,您可能需要使用CreateDateTime
函数:
using System.Data.Entity;
...
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate.Year)
.Select(c => new
{
Amount = c.Sum(b => b.Amount),
Date = EntityFunctions.CreateDateTime(c.Key, 1, 1, 0, 0, 0)
});