Search code examples
c#listlinqlinq-group

How to group a list of grouped lists?


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


Solution

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