请考虑以下记录:
Id Week Value
-----------------------------
1 1 1000
2 1 1200
3 2 800
4 3 1800
5 3 1100
6 3 1000
我想将记录分组4周,但我们没有记录第4周。例如:
Week Count
---------------------
1 2
2 1
3 3
4 0
我如何用linq做到这一点?
由于
答案 0 :(得分:2)
首先,您需要一周的数组,然后此查询可能会有所帮助
var weeks = new List<int>{1,2,3,4}
var q = from w in weeks
join rw in (
from r in table
group r by r.Week into g
select new {week = g.Key, count = g.Count()}) on w equals rw.week into p
from x2 in p.DefaultIfEmpty()
select new {w, count = (x2 != null ? x2.count : 0)};
答案 1 :(得分:0)
你可以尝试
var result = Enumerable.Range(1, 4)
.GroupJoin(table,
week => week,
record => record.Week,
(week, records) => new { Week = week, Count = records.Count() });
根据jessehouwing的建议,Enumerable.Range将返回可能用作连接中左外键的周数。
此致 丹尼尔。