I'm using LINQ to group ratings by month for the last 12 months and outputting JSON like this:
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)
});
If I have data for October and November, then my result looks like this:
Average: [3.5, 4] Dates: ["Oct", "Nov"]
How do I prefill up to the previous 12 months with 0's? So I should get results from Dec 2015 to Nov 2016 with Dec 2015 -> Sept 2016 showing as 0's.