开发者

Quick linq count question

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
              g开发者_运维技巧roup 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 union on 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:

  1. Define your date range (since you mention no end date in your code and we're talking about login date, I'm assuming that the end date would be the current date.
  2. Use Enumerable.Range to create a list of numbers ranging from 0 to the number of days within your date range, then use Select to 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 type
  3. Combine your lists together using an outer join (not the most obvious syntax in LINQ, unfortunately) on the Date property
  4. Order your results by date

This 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.

var allDates = Enumerable.Range(0, (DateTime.Today - startDate).TotalDays)
              .Select(i => new { Count = 0, Date = startDate.AddDays(i) });

var fullResults = from d in allDates
                  join r in results on d.Date == r.Date
                  from oj in r.DefaultIfEmpty()
                  select new { Count = oj == null ? 0 : oj.Count, Date = d.Date };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜