Search code examples
c#linqdatelinq-group

LINQ - Group List<T> to Year, Month, Day


I have a simple list

  • T.Date = 11/04/2014, T.Title = "Book1", T.Tipology = "Book"
  • T.Date = 14/04/2014, T.Title = "Book2", T.Tipology = "Book"
  • T.Date = 02/05/2015, T.Title = "Spot1", T.Tipology = "Spot"
  • T.Date = 21/06/2015, T.Title = "Newspaper1", T.Tipology = "Newspaper"

I need to group this list by Year, Month and Day as below:

  • 2014
    • April
      • T.Date = 11/04/2014, T.Title = "Book1", T.Tipology = "Book"
      • T.Date = 14/04/2014, T.Title = "Book2", T.Tipology = "Book"
  • 2015
    • May
      • T.Date = 02/05/2015, T.Title = "Spot1", T.Tipology = "Spot"
    • June
      • T.Date = 21/06/2016, T.Title = "Newspaper1", T.Tipology = "Newspaper"

So i will able to process data in a foreach function like:

 foreach(var year in Year)
 {
     foreach(var month in Month)
     {
         foreach(var day in Day)
         {
            Console.WriteLine(day.Item.Title);
            Console.WriteLine(day.Item.Tipology);
         }
         Console.WriteLine(month.ToString()); // With culture
     }
     Console.WriteLine(year.ToString());
 }

How I can do this with (c#) LINQ?


Solution

  • You can use nested groups.

    var groups = list
                .GroupBy(
                        d => d.Date.Year, 
                        (key, g) => g.GroupBy(
                                              d => d.Date.Month,
                                              (key2, g2) => g2.GroupBy(d => d.Date)
                                             )
                        );