简体   繁体   中英

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM