I have a table that records when a user views a page. The table looks something like this:
ID | Date
1 | 01/01/10 00:00:01.000
2 | 03/01/10 00:00:01.000
3 | 03/01/10 00:00:02.000
4 | 04/01/10 00:00:01.000
5 | 05/01/10 00:00:01.000
6 | 05/01/10 00:00:02.000
7 | 05/01/10 00:00:03.000
Using Linq-to-SQL I want to count the last group of consecutive days a page was viewed, but of course I’m not sure how I would go about doing this. For example, running the query on the data above should return 3.
Any help would be muchly appreciated 🙂
This is the test data. I added 6th Oct at the end of list to make sure the result only pick up last consecutive date set.
First, we need to find out the last consecutive date:
We have 2 choices here, to use
foreachorLINQ?foreachis more readable compared toLINQ. I will show both implementations.This is the implementation for
foreach:This is the implementation for
LINQ, less readable:Console.WriteLine(consecutiveDates.Count());will print out “3”.I am expecting more refactoring on my code, but I am off for break.