Linq to sql 如何按天将Linq到SQL结果分组并包括每个组的计数?
我需要获得在一个时间跨度内创建的所有CustomerOrder,按天对它们进行分组(不管当天是什么时间),然后还包括每天的CustomerOrder计数。我的ChartDateCount类有两个属性-Date和Count 下面是一些SQL数据示例:Linq to sql 如何按天将Linq到SQL结果分组并包括每个组的计数?,linq-to-sql,group-by,Linq To Sql,Group By,我需要获得在一个时间跨度内创建的所有CustomerOrder,按天对它们进行分组(不管当天是什么时间),然后还包括每天的CustomerOrder计数。我的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
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()
我想你在找
g.Key
Select New ChartDateCount With {.Date = g.Key, .Count = g.Count()}
Key属性包含按其分组的值
我想出了一个办法,但如果有人有更有效的办法,我肯定会给你一个奖励
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()
Dim chartData作为列表(ChartDateCount的)=_
(
来自dc.CustomerOrders中的co_
公司创建地点>起始日期_
和公司创建了
I get:'Key'不是'System.Collections.Generic.IEnumerable(属于CustomerOrders)'的成员。我还尝试了g.Created和g(0)。Created,但它也不允许这样做。我可以在LinqPad4中看到g是CustomerOrder的IEnumerable,但我似乎无法深入研究它以从中获取数据。奇怪的是,如果我可以用g来计算项目,为什么我不能遍历它们来获取数据呢(
Select New ChartDateCount With {.Date = g.Key, .Count = g.Count()}
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()