I'm trying to chart the number of registrations per day in our registration system. I have an Attendee table in sql server that has a smalldatetime field A_DT, which is the date and time the person registered.
I started with this:
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();
That works great, but it won't include the dates where there were no registrations, because there are no attendee records for those dates. I want every date to be included, and when there is no data for a given date, the count should just be zero.
So this is my current working solution, but I KNOW THAT IT IS TERRIBLE. I added the following to the code above:
// 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
});
}
So I created ANOTHER list, and loop through a sequence of dates I generate based on the first and last registrations in the query, and for each item in the sequence of dates, I QUERY the results of my first QUERY for the information regarding the given date, and supply a default if nothing comes back. So I end up doing a subquery here and I want to avoid this.
Can anyone thing of an elegant solution? Or at least one that is less embarrassing?