I have the following query that returns the login count per day from a given date.
var sot = from uts in DataContext.UserTrackingStatistics
let startDate = new DateTime(2009, 10, 01)
where uts.LastLogin >= startDate
group uts by uts.LastLogin.Date into myGroup
orderby myGroup.Key.Date
select new { Count = myGroup.Count() , myGroup.Key.Date};
I would like this to say the count was 0 for a given day rather than not return anything. How could I do that within this query?
You can’t do it just with LINQ-to-SQL, as you’d have to use a
unionon your query with data that doesn’t actually exist, which LINQ-to-SQL can’t do.To do this, you’ll need to fill in the gaps client-side. I’m not in front of VS at the moment, but a general approach would be this:
Enumerable.Rangeto create a list of numbers ranging from 0 to the number of days within your date range, then useSelectto transform that list into a list of dates. Select your results using an anonymous type and use the same properties as your L2S statement; this way, the compiler will reuse the same typeDatepropertyThis will now show 0 for the gaps.
I’ll try to post a code sample below, but note that I can’t compile where I am, so it may require tweaking.