gpt4 book ai didi

c# - 使用 linq 按日期分组查询填充缺失日期

转载 作者:太空狗 更新时间:2023-10-29 19:44:42 25 4
gpt4 key购买 nike

我有一个 Linq 查询,基本上计算在特定日期创建了多少条目,这是通过按年、月、日分组来完成的。问题是,因为有些日子没有任何条目,我需要用 0 计数的条目回填那些缺失的“日历日”。我的猜测是,这可能可以通过 Union 之类的东西来完成,或者甚至可以通过一些简单的 for 循环来处理查询后的记录。

这里是查询:

from l in context.LoginToken
where l.CreatedOn >= start && l.CreatedOn <= finish
group l by
new{l.CreatedOn.Year, l.CreatedOn.Month, l.CreatedOn.Day} into groups
orderby groups.Key.Year , groups.Key.Month , groups.Key.Day
select new StatsDateWithCount {
Count = groups.Count(),
Year = groups.Key.Year,
Month = groups.Key.Month,
Day = groups.Key.Day
}));

如果我有 12/1 - 12/4/2009 的数据(简化):

12/1/2009 20
12/2/2009 15
12/4/2009 16

我想要通过代码添加一个带有 12/3/2009 0 的条目。

我知道一般来说,这应该在数据库中使用非规范化表来完成,您可以在该表中填充数据或连接到日历表,但我的问题是如何在代码中完成此操作?
可以在Linq中完成吗?应该在 Linq 中完成吗?

最佳答案

我今天刚做的。我从数据库中收集了完整的数据,然后生成了一个“示例空”表。最后,我对空表与实际数据进行了外部联接,并使用 DefaultIfEmpty() 构造来处理了解数据库何时缺少行以使用默认值填充它。

这是我的代码:

int days = 30;

// Gather the data we have in the database, which will be incomplete for the graph (i.e. missing dates/subsystems).
var dataQuery =
from tr in SourceDataTable
where (DateTime.UtcNow - tr.CreatedTime).Days < 30
group tr by new { tr.CreatedTime.Date, tr.Subsystem } into g
orderby g.Key.Date ascending, g.Key.SubSystem ascending
select new MyResults()
{
Date = g.Key.Date,
SubSystem = g.Key.SubSystem,
Count = g.Count()
};

// Generate the list of subsystems we want.
var subsystems = new[] { SubSystem.Foo, SubSystem.Bar }.AsQueryable();

// Generate the list of Dates we want.
var datetimes = new List<DateTime>();
for (int i = 0; i < days; i++)
{
datetimes.Add(DateTime.UtcNow.AddDays(-i).Date);
}

// Generate the empty table, which is the shape of the output we want but without counts.
var emptyTableQuery =
from dt in datetimes
from subsys in subsystems
select new MyResults()
{
Date = dt.Date,
SubSystem = subsys,
Count = 0
};

// Perform an outer join of the empty table with the real data and use the magic DefaultIfEmpty
// to handle the "there's no data from the database case".
var finalQuery =
from e in emptyTableQuery
join realData in dataQuery on
new { e.Date, e.SubSystem } equals
new { realData.Date, realData.SubSystem } into g
from realDataJoin in g.DefaultIfEmpty()
select new MyResults()
{
Date = e.Date,
SubSystem = e.SubSystem,
Count = realDataJoin == null ? 0 : realDataJoin.Count
};

return finalQuery.OrderBy(x => x.Date).AsEnumerable();

关于c# - 使用 linq 按日期分组查询填充缺失日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1468637/

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