LINQ - 组列表<t>到年,月,日

时间:2015-06-24 12:19:55

标签: c# linq date linq-group

我有一个简单的清单

  
      
  • 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      
        
    • 四月      
          
      • T.Date = 11/04/2014,T.Title =“Book1”,T.Tipology =“Book”
      •   
      • T.Date = 14/04/2014,T.Title =“Book2”,T.Tipology =“Book”
      •   
    •   
  •   
  • 2015      
        
    • 五月      
          
      • T.Date = 02/05/2015,T.Title =“Spot1”,T.Tipology =“Spot”
      •   
    •   
    • 六月      
          
      • 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做到这一点?

4 个答案:

答案 0 :(得分:3)

您可以按年,月和日订购它们:

$sp = New-Object -TypeName Microsoft.SqlServer.Management.SMO.StoredProcedure -argumentlist $db, "GetUserPhoneForService"

如果您真的想将它们分组,那么您可以执行以下操作:

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

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

答案 1 :(得分:3)

您可以使用嵌套组。

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

答案 2 :(得分:0)

您的对象可以继承IComparable,而不仅仅是您的对象。

答案 3 :(得分:0)

您可以订购列表,然后跟踪上一本书:

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