我正在使用 LINQ 按月对过去 12 个月的评分进行分组,并像这样输出 JSON:
var startDate = DateTime.Now.AddMonths(-13);
var ratings = db.Ratings
.Where(x => x.RatingDate > startDate)
.GroupBy(c => new { Year = c.RatingDate.Year, Month = c.RatingDate.Month })
.ToList()
.Select(c => new
{
Date = new DateTime(c.Key.Year, c.Key.Month, 1),
Month = new DateTime(c.Key.Year, c.Key.Month, 1).ToString("MMM"),
Average = c.Average(d => d.Rating)
})
.OrderBy(a => a.Date);
return Json(new
{
Average = ratings.Select(x=>x.Average),
Dates = ratings.Select(x=>x.Month)
});
如果我有 10 月和 11 月的数据,那么我的结果如下所示:
平均:[3.5, 4] 日期:[“十月”,“十一月”]
如何用 0 预填充前 12 个月?所以我应该得到 2015 年 12 月到 2016 年 11 月的结果,2015 年 12 月 -> 2016 年 9 月显示为 0。
最佳答案
这是另一种与您最终采用的方式非常相似的方式。
var now = DateTime.Now.AddDays(1 - DateTime.Now.Day);
var months = Enumerable.Range(-11, 12)
.Select(m => new DateTime(now.AddMonths(m).Year, now.AddMonths(m).Month, 1));
var ratingsByMonth =
from date in months
let month = new { Year = date.Year, Month = date.Month }
join r in ratings
on month equals new { r.RatingDate.Year, r.RatingDate.Month }
into g
select new {
Date = month,
Rating = g.Count() > 0 ? g.Average(x => x.Rating) : 0
};
关于c# - 使用 linq 按具有空数据值的日期进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40838286/