我正在计算每天创建的用户数,如下所示:
IEnumerable<DateTime> dates = GetAllDatesForPeriod();
var rows = context.Users
.Where(x => x.Created >= minDate && x.Created <= max.Date)
.GroupBy(x => new { Year = x.Created.Year, Month = x.Created.Month, Day = x.Created.Day })
.Select(x => new { Year = x.Key.Year, Month = x.Key.Month, Day = x.Key.Day, Count = x.Count() }).ToList()
.Select(x => new DataModel { Date = new DateTime(x.Year, x.Month, x.Day), Users = x.Count }).ToList();
rows.AddRange(dates.Where(x => !rows.Any(y => y.Date == x)).Select(x => new DataModel { Date = x, Users = 0 }));
第二个 Select 是因为我无法在 Ef 查询中创建 DateTime。
AddRange 是用 Count = 0 填充缺失的日期。
此代码正在运行。但是有没有办法简化这个?
谢谢你,米格尔