按实体框架分组记录并填补空白

时间:2014-02-28 12:34:11

标签: c# entity-framework entity-framework-6

Grouping records hour by hour or day by day and filling gaps with zero or nullGrouping records hour by hour or day by day and filling gaps with zero or null in mysql之前有一个类似的问题,但两个解决方案都使用SQL。我想用代码来解决这个问题。

最简单的解决方案是运行:

var q = from i in XXX.Table
    let dt = p.Date
    group i by new { y = dt.Year, m = dt.Month, d = dt.Day, h = dt.Hour}
    select g;

但是我还有很多空白要填补。

1 个答案:

答案 0 :(得分:0)

您可以从服务器获取组并填补客户端上的空白:

var startDate = new DateTime(2014, 1, 2);
var endDate = new DateTime(2014, 1, 3);

var dict = (from c in YourTable
  where c.YourDate >= startDate && c.YourDate <= endDate 
  let hours = DbFunctions.DiffHours(startDate, c.YourDate)
  group c by hours into g 
  select new {Hour = g.Key, Count = g.Count()}).ToDictionary(r => r.Hour.Value, r => r.Count);

var result = Enumerable.Range(0, (int)(endDate - startDate).TotalHours).Select(h => new {Date = startDate.AddHours(h), Count = dict.ContainsKey(h) ? dict[h] : 0});