【发布时间】:2011-10-07 17:02:00
【问题描述】:
我想使用 Linq to Entities 将活动列表汇总为上周按天出现的次数。例如,假设我的数据库中有这样的数据:
Id | Date
1 | 2011-09-30 0:00:0
2 | 2011-10-02 0:00:00
3 | 2011-10-02 0:00:00
4 | 2011-10-02 0:00:00
5 | 2011-10-04 0:00:00
6 | 2011-10-04 1:30:30
7 | 2011-10-04 0:00:00
8 | 2011-10-06 0:00:00
假设今天的日期是 2011-10-07
我想生成以下内容:
Date | Count
2011-10-01 | 0
2011-10-02 | 3
2011-10-03 | 0
2011-10-04 | 3
2011-10-05 | 0
2011-10-06 | 1
2011-10-07 | 0
这是我可以用来按日期对事件进行分组的示例技术,但我缺少零。
// Using Linq to Objects for demonstration purpose only
var activities = new List<Activity>();
activities.Add(new Activity { Id = 1, Date = new DateTime(2011, 9, 30)});
activities.Add(new Activity { Id = 2, Date = new DateTime(2011, 10, 2)});
activities.Add(new Activity { Id = 3, Date = new DateTime(2011, 10, 2)});
activities.Add(new Activity { Id = 4, Date = new DateTime(2011, 10, 2)});
activities.Add(new Activity { Id = 5, Date = new DateTime(2011, 10, 4)});
activities.Add(new Activity { Id = 6, Date = new DateTime(2011, 10, 4, 1, 30, 30) });
activities.Add(new Activity { Id = 7, Date = new DateTime(2011, 10, 4)});
activities.Add(new Activity { Id = 8, Date = new DateTime(2011, 10, 6)});
var data = (from a in activities
group a by a.Date.Date into g
where g.Key > DateTime.UtcNow.AddDays(-7)
select new {
Date = g.Key,
Count = g.Count()
}).ToList();
结果如下:
Date | Count
2011-10-02 | 3
2011-10-04 | 3
2011-10-06 | 1
有人知道我如何使用 Linq to Entities 包含缺失的零吗?一旦我将结果存储在内存中,我总是可以枚举结果,但是直接从数据库中获取它会很好。
【问题讨论】:
-
直接从数据库中获取?它首先不在数据库中,因为您正在生成缺失的日期。仅使用 for 循环 IMO 可能会更容易、更有效。
标签: c# linq entity-framework linq-to-entities