madlan
madlan

Reputation: 1397

LINQ - Group by Year and Month

I'm trying to write a linq query to group data from a datatable by year\month.

I've managed to group by one or the other but not both...

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

How do I group\order by year THEN month within the same query?

Source data:

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

Expected output:

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

Upvotes: 3

Views: 3826

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460048

You need to group by an anonymous type of two properties(year+month). You also need to apply the Key keyword in VB.NET.

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

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

You need to create an anonymous type containing the two values or you can use a tuple:

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

Upvotes: 0

Related Questions