3

我正在尝试编写一个 linq 查询来按年\月对数据表中的数据进行分组。

我已经设法按一个或另一个分组,但不是同时...

       Dim q = From p As DataRow In DTCalls.Rows _
                Group By Year = p("DATE").Year _
                Into CALLS = Count(p("CALL_ID")) _
                Select Year, CALLS

如何在同一查询中按年 THEN 月分组\排序?

源数据:

DATE                    CALL_ID
2012-05-01 23:52:44   6587
2012-02-03 09:17:41   6562
2012-05-01 06:32:41   6565
2012-02-03 12:47:41   6565
2011-05-31 08:37:41   6511

预期输出:

DATE       COUNT
2011-05      1
2012-02      2
2012-05      2
4

2 回答 2

3

您需要按两个属性(年+月)的匿名类型进行分组。您还需要Key在 VB.NET 中应用关键字。

匿名类型 (Visual Basic)

Dim dateGroups =
    From row In table
    Let year = row.Field(Of Date)("DATE").Year
    Let month = row.Field(Of Date)("DATE").Month
    Group row By YearMonth = New With {
        Key .year = year,
        Key .month = month
    } Into DateGroup = Group
    Order By YearMonth.year, YearMonth.month

For Each grp In dateGroups
    Console.WriteLine("Date: {0}-{1} Count:{2}",
                      grp.YearMonth.year,
                      grp.YearMonth.month,
                      grp.DateGroup.Count())
Next
于 2012-10-10T14:25:28.023 回答
0

您需要创建一个包含这两个值的匿名类型,或者您可以使用元组:

Group By Tuple.Create(p("DATE").Year, p("DATE").Month)
于 2012-10-10T14:17:29.593 回答