1

我正在计算每天创建的用户数,如下所示:

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 填充缺失的日期。

此代码正在运行。但是有没有办法简化这个?

谢谢你,米格尔

4

1 回答 1

1

这是主要查询:

var rows = context.Users
    .Where(x => x.Created >= minDate && x.Created <= max.Date)
    .GroupBy(u => EntityFunctions.TruncateTime(u.Created))
    .Select(g => new DataModel { Date = g.Key, Count = g.Count() }).ToList();

之后,您可以像以前一样添加缺失的日期。

于 2012-10-10T22:05:40.520 回答