【问题标题】:How to group Linq to SQL results by Day and include the counts of each group?如何按天对 Linq to SQL 结果进行分组并包括每组的计数?
【发布时间】:2012-09-18 14:18:44
【问题描述】:

我需要获取在一个时间跨度内创建的所有 CustomerOrders,按天对它们进行分组(无论当天什么时间),然后还包括每天的 CustomerOrders 计数。我的 ChartDateCount 类有两个属性 - Date 和 Count。

所以,这里有一些示例 SQL 数据:

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  

我的输出应该是:

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

这是我目前所拥有的。

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()

我有点接近这个,但我无法让 Date 填充:

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()}

更新

理论上这正是我想要做的(见下文),但我收到一个错误这个错误: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()}

【问题讨论】:

    标签: linq-to-sql group-by


    【解决方案1】:

    我想你在找g.Key

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

    Key 属性包含分组依据的值。

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

    【讨论】:

    • 我得到:'Key' 不是 'System.Collections.Generic.IEnumerable(Of CustomerOrders)' 的成员。
    • 我也试过 g.Created 和 g(0).Created 但它也不允许这样做。我可以在 LinqPad4 中看到 g 是 CustomerOrders 的 IEnumerable,但我似乎无法深入研究它以从中获取数据。如果我可以计算 g 中的项目,这很奇怪,为什么我不能遍历它们来获取数据? :(
    【解决方案2】:

    我想出了一个方法,但如果有人有更有效的方法来解决这个问题,我肯定会给予你信任......

    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()
    

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多