C# 从datatable中按日期分组并每两小时获取一次记录

C# 从datatable中按日期分组并每两小时获取一次记录,c#,linq,C#,Linq,我有一个datatable,它的列是name、code、date和time。现在我想使用LINQ获得一天中每小时的所有记录的计数 DateTime列包含以下数据: 2018-08-01 07:00:06.163 2018-08-01 07:50:11.873 2018-08-01 08:00:42.623 2018-08-01 07:20:48.363 2018-08-01 09:01:15.243 2018-08-01 06:01:16.507 现在,我想按小时计算从一天开始到一天结束的所有

我有一个datatable,它的列是name、code、date和time。现在我想使用LINQ获得一天中每小时的所有记录的计数

DateTime列包含以下数据:

2018-08-01 07:00:06.163
2018-08-01 07:50:11.873
2018-08-01 08:00:42.623
2018-08-01 07:20:48.363
2018-08-01 09:01:15.243
2018-08-01 06:01:16.507
现在,我想按小时计算从一天开始到一天结束的所有记录的数量

例如:
如果第一条记录是2018年8月1日上午5点左右,则其开始时间为第一排上午5点至7点

2018-08-01  7   ( 5 Am - 7 Am) - 36 count
2018-08-01  9   ( 7 Am - 9 Am) - 12 count
2018-08-01  11   ( 9 Am - 11 Am) - 12 count
2018-08-01  13  (11 Am - 1 PM)- 0 count
2018-08-01  15  (1 PM - 3 PM)- 36 count

您可以尝试以下代码:

const int groupHours = 2;
const int driftHours = 1;
var dateTimes = new List<DateTime>() { new DateTime(2018, 8, 30, 7, 0, 6), new DateTime(2018, 8, 30, 8, 0, 6) };
var result = dateTimes.GroupBy(d => new DateTime(d.Year, d.Month, d.Day, (((d.Hour - driftHours) / groupHours) + 1) * groupHours + driftHours, 0, 0)).Select(g => new { Key = g.Key, Count = g.Count() });
const int groupHours=2;
常数int漂移小时=1;
var dateTimes=new List(){new DateTime(2018,8,30,7,0,6),new DateTime(2018,8,30,8,0,6)};
var result=dateTimes.GroupBy(d=>newdatetime(d.Year,d.Month,d.Day,((d.Hour-flofthours)/groupHours)+1)*groupHours+flofthours,0,0))。选择(g=>new{Key=g.Key,Count=g.Count());
上午8点的
((d.Hour-driftHours)/groupHours)+1)*groupHours+driftHours
示例:

  • 从上午8点到上午7点减去1(从可被2整除的正则数中漂移的小时数)
  • 除以2(小组中的小时跨度),并在小数点后删除所有内容-到目前为止有多少个“小组”
  • 将1添加到上一个结果以获得当前组
  • 乘以2(组中的小时跨度)得到该组的小时数
  • 加1(漂移)使8取9,10取11等

到目前为止,您尝试了什么来解决这个问题?用户
计时器
后台工作人员/任务。运行(()=>linq)
Szymon Chęciński感谢您的帮助,它工作正常