LINQ - 组列表<T> 到年、月、日

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

我有一个简单的列表

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

我需要按年月日对列表进行分组,如下所示:

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

所以我将能够在 foreach 函数中处理数据,例如:

 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());
 }

如何使用 (c#) LINQ 执行此操作?

您可以按年月日排序:

var sorted = list.OrderBy(x=>x.Date.Year)
                 .ThenBy(x=>x.Date.Month)
                 .ThenBy(x=>x.Date.Day);

如果你真的想把它们分组,那么你可以这样做:

var result = from l in list
             group l by new { l.Date.Year,l.Date.Month} into g 
             select new
                   {
                     Year = g.Key.Year,
                     Month = g.Key.Month,
                     Items = g.ToList()
                    };

因此它将为您提供每年月份日期的分组数据

您可以使用嵌套组。

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

您的对象可以继承自 IComparable,而不仅仅是按您的对象排序。

您可以订购清单,然后跟踪最后一本书:

var orderedBooks = books.OrderBy(x => x.Date.Year).ThenBy(x => x.Date.Month).ThenBy(x => x.Date.Day);
Book last = null;
foreach (Book book in orderedBooks)
{
    Console.WriteLine(book.Title);
    Console.WriteLine(book.Tipology);
    if(last != null  && last.Date.Month != book.Date.Month)
        Console.WriteLine(DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(book.Date.Month)); // With culture
    if (last != null && last.Date.Year != book.Date.Year)
        Console.WriteLine(book.Date.Year.ToString()); 
    last = book;
}