即使某些月份不包含任何数据,我也希望能够按月份对所有数据进行分组。此时,我可以分组,但返回的数据只包含月份数据。
这是我的代码的样子:
var twelveMonthAgo = date.AddMonths(-12).Date;
var twelveMonthAgoFirstOfMonth = new DateTime(twelveMonthAgo.Year, twelveMonthAgo.Month, 1, 0, 0, 0, 0);
var data = (from i in Database.Users
where i.RegisterDate >= twelveMonthAgoFirstOfMonth
group i by new {y=i.RegisterDate.Year,m = i.RegisterDate.Month} into g
select new UserStatistic{ Date = EntityFunctions.CreateDateTime(g.Key.y, g.Key.m, 1, 0, 0, 0)
, UserCount = g.Count(o => o.Id)
});
//The code below is what I would like to remove
var toReturn = new List<UserStatistic>();
var allData = data.ToList();
DateTime datei = twelveMonthAgoFirstOfMonth;
while (datei.Year<= date.Year && datei.Month<=date.Month){
var info = allData.SingleOrDefault(x => x.Date.HasValue && x.Date.Value.Year == datei.Year && x.Date.Value.Month == datei.Month);
toReturn.Add(info ?? new UserStatistic { Date = datei, UserCount = 0, PaymentPaid = 0 });
datei = datei.AddMonths(1);
}
return toReturn.AsQueryable();
如您所见,注释下的代码构建了一个最近 12 个月的集合,并检查是否有一些数据已从数据库中取出,如果存在则填充该集合,否则输入 0。
我怎样才能做到这一切而无需在评论下方执行代码?