Message group by year, then by month

I need help with LINQ-2-SQL to group some blog posts by year and month.

Basically, I have a collection of blog posts that have the following properties

  • Id
  • Title
  • date

I want every month of this year to go through an iteration, then repeat every month of this year, and finally repeat every blog post for that month. Something like

  • 2011
    • April (show the number of posts)
      • Random Article 1
      • Random Article 2
    • May (show the number of publications)
      • Random Article 2

etc.

Is there a way to do this with a single LINQ query using a group by clause?

Here, as far as I know,

var groupedBlogPosts = (from p in blogPostsFiltered group p by new { month = p.Date.Month, year = p.Date.Year } into d select new { postDate = string.Format("{0}/{1}", d.Key.month, d.Key.year), postCount = d.Count() }); 
+7
source share
2 answers

I really haven't tested this, but it looks like a start, wrote this by looking at this msdn article :

 var groupedBlogPosts = from p in blogPostsFiltered group p by p.Date.Year into yg select new { Year = yg.Key, MonthGroups = from o in yg group o by o.Date.Month into mg select new { Month = mg.Key, Posts = mg } }; 

Look under the heading GroupBy - Nested .

+9
source

Here is an alternative if you do not want to make forecasts and leave them as groupings.

 var groupedBlogPosts = from post in blogPostsFiltered group post by new { post.Date.Year, post.Date.Month } into grouped group grouped by new { grouped.Key.Year }; 
+5
source

All Articles