LINQ-to-SQL Grouping By Week
I came across the problem of requiring to group items from my SQL database by week yesterday. After a quick Google search, I found a few other people were having the same problem. Although I must admit this was not hard, it might not seem immediately obvious to everyone.
The following code example will group items from a database by week, and is supported by SQL Server:
var byWeek = from t in ctx where t.Date >= startWeek && t.Date < endWeek group t by t.DateFieldInDb.Date.AddDays(-(int)t.DateDateFieldInDb.DayOfWeek) into tw orderby tw.Key select new { Date = tw.Key, Count = tw.Count() };
I should note that this groups weeks starting with Sunday. To start with Monday, you could try the following code (untested, but should work):
var byWeek = from t in ctx where t.Date >= startWeek && t.Date < endWeek group t by t.DateFieldInDb.Date.AddDays(-((int)t.DateFieldInDb.DayOfWeek == 0 ? 6 : (int)t.DateFieldInDb.DayOfWeek - 1)) into tw orderby tw.Key select new { Date = tw.Key, Count = tw.Count() };
And that’s it, simple as that. Let me know if you find this useful, or find a better way!
3 Comments to LINQ-to-SQL Grouping By Week
Really helpful…
I used it in my Application. Earlier I was using SQL Procedure to pull this kind of data, but this seems faster then that…
Thanks a lot.
Buy:Cialis Soft Tabs.Maxaman.Cialis Professional.VPXL.Tramadol.Viagra Soft Tabs.Viagra Professional.Super Active ED Pack.Soma.Viagra.Levitra.Propecia.Viagra Super Active+.Cialis Super Active+.Cialis.Zithromax.Viagra Super Force….
Stools http://aremcraftmda.AUTOTECHGUIDE.INFO/tag/Home+Bar+Sets+Stools+dining+with/ : Stools…
Home…
December 10, 2009