1

I need a grouped list of grouped lists; I have a bunch of articles that I need to group by year, and group by month within each year. It will look something like this on the page:

2015

February

Article 1 Title

Article 2 Title

January

Article 3 Title


2014

December

Article 4 title


I know how to get one grouped list, such as

var yearList = articles.GroupBy(x => x.Year);

But how can I group a list of grouped lists?

This is my article class:

public class Article
{
    public String Title { get; set; }
    public String DateDisplay { get; set; }
    public String MoreLink { get; set; }
    public int Month { get; set; }
    public int Year { get; set; }
}

I want a grouped list by Year, that contains grouped lists by month

ekad
  • 14,436
  • 26
  • 44
  • 46
Erica Stockwell-Alpert
  • 4,624
  • 10
  • 63
  • 130

2 Answers2

5

Supposing you have an Article class with Year and Month properties, this will do:

var perYearAndPerMonth = articles.GroupBy(a => a.Year)
                                 .Select(yearGroup => new
                                 {
                                     Year = yearGroup.Key,
                                     PerMonth = yearGroup.GroupBy(a => a.Month)
                                                         .Select(monthGroup => new
                                                         {
                                                             Month = monthGroup.Key,
                                                             Articles = monthGroup.ToList()
                                                         })
                                 });

Converting the month groupings to an anonymous type is of course not necessary, but makes it more clear what you actually get in the result.

Habib
  • 219,104
  • 29
  • 407
  • 436
twoflower
  • 6,788
  • 2
  • 33
  • 44
1

Each item in your sequence is a group, to transform each item in your sequence into something else, use Select. Within that Select you need to transform each group into a sequence of groups. To actually transform the one group into a sequence of groups, use GroupBy.

Servy
  • 202,030
  • 26
  • 332
  • 449