gpt4 book ai didi

c# - Linq:计算行组,包括 0 行缺失行

转载 作者:行者123 更新时间:2023-11-30 12:15:17 25 4
gpt4 key购买 nike

我想使用 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 包含缺失的零吗?一旦我将结果存入内存,我总是可以枚举结果,但直接从数据库中获取结果会更好。

最佳答案

使用循环生成可能同样容易,因为数据在数据库中已经不可用,并且通过 LINQ 生成它会很复杂:

var firstDate = data.Min(d => d.Date).AddDays(-1);
var lastDate = data.Max(d => d.Date).AddDays(1);

for (var date = firstDate; date <= lastDate; date = date.AddDays(1))
if (!data.Exists(d => d.Date == date))
data.Add(new { Date = date, Count = 0 });

data = data.OrderBy(d => d.Date);
// do something with data

除非您的数据集真的非常大,否则与数据库请求所花费的时间相比,这种内存中的查询和列表调整将是微不足道的。

关于c# - Linq:计算行组,包括 0 行缺失行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7690481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com