【问题标题】:LINQ - Group by Year and MonthLINQ - 按年和月分组
【发布时间】:2012-10-10 22:46:44
【问题描述】:

我正在尝试编写一个 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

【问题讨论】:

  • 在您的示例中,您可以简单地按日期分组。您应该展示一个在同一年/月中有两个日期的示例。
  • 抱歉,示例数据有误。 (更新)

标签: vb.net linq


【解决方案1】:

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

Anonymous Types (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 年 3 月有两个条目,2011 年 3 月有一个条目。
  • 同时 OP 已编辑问题以提供更好的样本数据。但是,答案无论如何都应该有效。 (编辑它以提供正确的顺序)
  • 太棒了 :) 我正在使用 dateGroups.ToList() 测试您的第一次编辑以绑定到 datagridview。
【解决方案2】:

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

Group By Tuple.Create(p("DATE").Year, p("DATE").Month)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2021-10-16
    相关资源
    最近更新 更多