LINQ左连接,分组依据和计数

时间:2016-02-13 11:34:43

标签: c# linq sql-to-linq-conversion

我试图计算每小时发送的邮件数量。但我的代码返回错误的结果

这是我使用的原始sqlite查询,它工作正常。

SELECT Hours.hour, ifnull(count(Messages.hour),0) as count Hours LEFT JOIN Messages on Messages.hour = Hours.hour by Hours.hour

但我是LINQ的新手,这是我的代码和查询。

int[] Hours = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 };

var sortByHour = from h in Hours
                 join m in Messages on h equals m.Hour into g
                 orderby h ascending
                 select new
                 {
                     Hour = h,
                     Total = g.Count()
                 };

然后返回

[0] { Hour = 0, Total = 33485 }
[1] { Hour = 1, Total = 0 }
[2] { Hour = 2, Total = 0 }
[3] { Hour = 3, Total = 0 }
...
[23] { Hour = 23, Total = 0 }

第一个数据有总行数,其他数据有0个错误。

结果应该是这样的

[0] { Hour = 0, Total = 501 }
[1] { Hour = 1, Total = 408 }
[2] { Hour = 2, Total = 181 }
[3] { Hour = 3, Total = 84 }
...
[23] { Hour = 23, Total = 1055 }

如何修复我的代码?谢谢你提前。

2 个答案:

答案 0 :(得分:2)

答案是

var res = from h in Hours
          join m in Messages on h equals m.Hour into jn
          from j in jn.DefaultIfEmpty()
          select new
          {
              hour = h,
              count = j != null ? jn.Count(i => i.Hour == h) : 0
          }

但是如果你有数据库,模型,小时和消息之间的关系,我们正在讨论linq to sql或lint to entities,它可以更好地使用(正如我们在评论中提到的那样)h.Messages.Count( )让数据库引擎发出请求

答案 1 :(得分:0)

这样的事情可以解决你的问题。

<强>设定:

int[] Hours = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
var Messages = new List<Message>()
                {
                    new Message() { MessageId = 1, Hour = 5 },
                    new Message() { MessageId = 2, Hour = 7 },
                    new Message() { MessageId = 3, Hour = 5 },
                    new Message() { MessageId = 4, Hour = 3 },
                    new Message() { MessageId = 5, Hour = 7 },
                    new Message() { MessageId = 6, Hour = 5 },
                };

<强>查询:

 var sortByHour = Hours.Select(h =>
    new { Hour = h, Total = Messages.Count(m => m.Hour == h) } );

基本上,您只需在Messages中选择每小时及其计数。