Linq嵌套分组

时间:2009-07-07 14:38:15

标签: vb.net linq grouping

我有一个大型项目表,我需要按类别组织它们,然后按年份然后按月组织。

项目具有CategoryID和Dated属性。

我到目前为止:

Dim Items = From Item In DB.Items _
        Group By CategoryID = Item.CategoryID _
        Into Categories = Group _
        Order By CategoryID 

但我把它放在:

        Group By Year = Year(Item.Dated) 

        Group By Month = Month(Item.Dated)  

最终结果应该是这样的:

For Each Category in Categories
 For Each Year in Category.Years
  For Each Month in Year.Months
   For Each Item in Month.Items

   Next
  Next
 Next
Next

由于

1 个答案:

答案 0 :(得分:3)

阅读本文后(还有关于此主题的更多信息):

  

http://msdn.microsoft.com/en-us/vbasic/bb738024.aspx

我想出来了:

Dim Items = From Item In DB.Items _
  Group Item By CatID = Item.CatID Into Group Select CatID, _
  YearGroups = From y In Group _
    Group y By YearKey = y.PubDate.Value.Year Into YearGroup = Group _
    Select Year = YearKey, _
    MonthGroups = From m In YearGroup _
      Group m By MonthKey = m.PubDate.Value.Month Into MonthGroup = Group _
      Select Month = MonthKey, MonthItems = MonthGroup