0

There was a similar question before Grouping records hour by hour or day by day and filling gaps with zero or null and Grouping records hour by hour or day by day and filling gaps with zero or null in mysql but both solutuion use SQL. I would like to resolve this problem with code.

The easiest solution is to run:

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;

but I have got a lot of gaps still to fill.

Community
  • 1
  • 1
Piotr Stapp
  • 18,130
  • 10
  • 63
  • 104

1 Answers1

0

You can fetch groups from server and fill gaps on client:

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});
Ben
  • 2,272
  • 23
  • 32