在Grouping records hour by hour or day by day and filling gaps with zero or null和Grouping 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;
但是我还有很多空白要填补。
答案 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});