Groupby计数每小时计数值0

时间:2014-04-26 13:35:55

标签: c# asp.net list

我有一个人的名单,我想要每小时登记的人数。我使用了下面的GroupBy子句,我得到了正确的结果。

var persons = lstPerson.GroupBy(x =>(x.CreatedOn.Hour))
                       .Select(grp => new { total = grp.Count(), key = grp.Key })
                       .OrderBy(x => x.key)
                       .ToList();

但我想要每小时一次。它只显示计数的值。如果第一个小时没有人注册,那么它在列表中没有显示0个计数。

因此,例如,有人只注册了13,14,5小时(意味着在13:00,14:00和15:00),然后它显示了它的计数,但没有显示其他时间。

1 个答案:

答案 0 :(得分:0)

有两种选择:

首先,对代码进行最少更改,您只需向每个组“添加一个”,然后从每个计数中“减去一个”:

var persons = lstPerson
    .Select(x => (x.CreatedOn.Hour))  // Get the hours from the people
    .Concat(Enumerable.Range(0, 24))  // Add an extra copy of each hour
    .GroupBy(h => h)                      // ↓ subtract the extra hours
    .Select(grp => new { total = grp.Count() - 1, key = grp.Key })
    .OrderBy(x => x.key)
    .ToList();

其次,更整洁但涉及替换所有代码,您可以将人员列表加入到小时列表中:

var persons = Enumerable.Range(0, 24)
    .GroupJoin(
        lstPerson,
        h => h,                  // Correlate the hours in the range
        p => p.CreatedOn.Hour,   // with the hours from each person
        (h, ps) => new { total = ps.Count(), key = h))
    .ToList();    // ↑ This selects one element for each hour in the range
相关问题