【发布时间】:2008-09-29 19:18:50
【问题描述】:
我正在尝试在我们的注册系统中记录每天的注册数量。我在 sql server 中有一个 Attendee 表,它有一个 smalldatetime 字段 A_DT,这是该人注册的日期和时间。
我是从这个开始的:
var dailyCountList =
(from a in showDC.Attendee
let justDate = new DateTime(a.A_DT.Year, a.A_DT.Month, a.A_DT.Day)
group a by justDate into DateGroup
orderby DateGroup.Key
select new RegistrationCount
{
EventDateTime = DateGroup.Key,
Count = DateGroup.Count()
}).ToList();
这很好用,但它不包括没有注册的日期,因为这些日期没有与会者记录。我希望包含每个日期,并且当给定日期没有数据时,计数应该为零。
所以这是我目前的工作解决方案,但我知道这很糟糕。 我在上面的代码中添加了以下内容:
// Create a new list of data ranging from the beginning to the end of the first list, specifying 0 counts for missing data points (days with no registrations)
var allDates = new List<RegistrationCount>();
for (DateTime date = (from dcl in dailyCountList select dcl).First().EventDateTime; date <= (from dcl in dailyCountList select dcl).Last().EventDateTime; date = date.AddDays(1))
{
DateTime thisDate = date; // lexical closure issue - see: http://www.managed-world.com/2008/06/13/LambdasKnowYourClosures.aspx
allDates.Add(new RegistrationCount
{
EventDateTime = date,
Count = (from dclInner in dailyCountList
where dclInner.EventDateTime == thisDate
select dclInner).DefaultIfEmpty(new RegistrationCount
{
EventDateTime = date,
Count = 0
}).Single().Count
});
}
所以我创建了另一个列表,并循环遍历我根据查询中的第一次和最后一次注册生成的日期序列,对于日期序列中的每个项目,我查询我的第一个查询的结果以获取信息关于给定日期,如果没有返回,则提供默认值。所以我最终在这里做了一个子查询,我想避免这种情况。
任何人都可以提出一个优雅的解决方案吗?或者至少有一个不那么尴尬的?
【问题讨论】: