RichC
RichC

Reputation: 7879

How to group Linq to SQL results by Day and include the counts of each group?

I need to get all the CustomerOrders created within a time span, group them by day (regardless of what time during that day) and then also include the count of CustomerOrders for each day. My ChartDateCount class has two properties - Date and Count.

So, here is some example SQL data:

OrderID     Created
1           1/1/2012 04:30:12  
2           1/1/2012 05:15:29  
3           1/1/2012 07:09:45  
4           1/3/2012 01:12:21  
5           1/4/2012 06:33:58  
6           1/4/2012 08:30:26  
7           1/5/2012 10:17:41  
8           1/5/2012 11:30:43  
9           1/6/2012 01:11:11  

And my output should be:

Date         Count
1/1/2012     3
1/3/2012     1
1/4/2012     2
1/5/2012     2
1/6/2012     1

This is what I have so far.

Dim chartData as List(Of ChartDateCount) = _
         ( _
            From co In dc.CustomerOrders _
            Where co.Created >= fromDate _
            And co.Created <= toDate _
            Select New ChartDateCount With {.Date = ???, .Count = ???} _
         ).ToList()

I kind of got close with this one but I couldn't get Date to populate:

From co In CustomerOrders _
Where co.Created >= "1/1/2012" And co.Created <= "1/7/2012" _
Group co By co.Created.Value.Date Into g = Group _
        Select New ChartDateCount With {.Date = ????, .Count = g.Count()}

UPDATE

This is exactly what I want to do (see below) in theory but I get an error this error: The query operator 'ElementAtOrDefault' is not supported.

From co In CustomerOrders _
Where co.Created >= "1/1/2012" And co.Created <= "1/7/2012" _
Group co By co.Created.Value.Date Into g = Group _
        Select New ChartDateCount With {.Date = g(0).Created.Value.Date, .Count = g.Count()}

Upvotes: 0

Views: 551

Answers (2)

RichC
RichC

Reputation: 7879

I figured out a way but if anyone has a more efficient way of going about this, I will certainly give you credit instead...

Dim chartData as List(Of ChartDateCount) = _
    (
        From co In dc.CustomerOrders _
                Where co.Created > fromDate _
                   And co.Created < toDate _
            Group By co.Created.Value.Date Into g = Group _
                   Select New ChartNameValue With _
                   {
                      .Date = (From co2 As CustomerOrder In g).Take(1).Single().Created.Value.Date, _
                      .Count = g.Count()
                   }
     ).ToList()

Upvotes: 0

Aducci
Aducci

Reputation: 26694

I think you are looking for g.Key

 Select New ChartDateCount With {.Date = g.Key, .Count = g.Count()}

The Key property contains the value you grouped by.

http://msdn.microsoft.com/en-us/library/bb343251.aspx

Upvotes: 1

Related Questions