我想在c#中使用Linq将以下日期时间分组在一起,如下所示:
组1:
2015-03-03 15:18:42.880
2015-03-03 15:18:42.897
组2:
2015-03-19 16:29:59.977
2015-03-19 16:29:59.983
2015-03-19 16:29:59.983
集团3:
2015-03-26 11:27:29.813
2015-03-26 11:27:30.030
2015-03-26 11:27:30.030
第四组:
2015-03-27 15:13:58.483
2015-03-27 15:13:58.483
2015-03-27 15:13:58.500
我对其中一些分组有一个问题。目前,我只是对日期进行分组,忽略毫秒部分。我想要做的是把日期分组,时间间隔在1秒以内,没有毫秒。这是我到目前为止的查询:
var query =
from trans in TransactionTable.AsEnumerable()
let dateWithoutMilliseconds = trans.Field<DateTime>("TranactionDate").AddMilliseconds(-trans.Field<DateTime>("TranactionDate").Millisecond)
group trans by dateWithoutMilliseconds into g
select new
{
TransDate = g.Key,
};
可以转换为Ticks
(100纳秒),四舍五入,然后返回到DateTime
。如果您只想要GroupBy
,只需四舍五入Tick
s:
DateTime source = ...
...
// Up to nearest second
const int shift = 10000000;
DateTime result = new DateTime(
(source.Ticks / shift + (source.Ticks % shift >= (shift / 2) ? 1 : 0)) * shift);
// If you want just a key to group by
long key = (source.Ticks / shift + (source.Ticks % shift >= (shift / 2) ? 1 : 0)) * shift;