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:
Article 1 Title
Article 2 Title
Article 3 Title
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
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.