如何使用LINQ按照C#中的特定时间戳记进行分组? [英] How can I group by specific timestamp intervals in C# using LINQ?

查看:197
本文介绍了如何使用LINQ按照C#中的特定时间戳记进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含tick对象的列表,包括一对双值和时间戳。

I have a list with tick objects including a pair of a double value and a timestamp.

我想根据时间将列表分成子列表间隔(例如15分钟)。一个列表只有从8:00:00 - 8:14-59 usw usw

I want to separate the list into child-lists depending on a time interval (for example 15 minutes). One list only has the tick objects from: 8:00:00 - 8:14-59 usw usw

var result = from tick in listTicks
group tick by tick.timestamp.Hour; 

datetime 功能如日,分钟工作不错,但是对我来说是不可能的。

The datetime functions like day, hour, minute work fine but a specific interval wasn't possible for me.

是对象的LINQ。我已经从数据库中获得了列表,我想转换列表。

It is LINQ to objects. I have already got the list from the DB and I want to transform the list.

如果我每天有8-22的数据分开到3 h,那么这样:

If I have data from 8-22 each day separate to 3 h he separate this way:


0-2; 3-5; 6-8; 9-11

0-2;3-5;6-8;9-11

使用代码:

var result = from tick in listTicks group tick by
(tick.timestamp.Day * 10 + tick.timestamp.Hour / 3);

我想要:


8-10; 11-13; 14-16; 17-19; 20-22

8-10;11-13;14-16;17-19;20-22

我想要

推荐答案

var result = from tick in listTicks
group tick by (tick.timestamp - DateTime.MinValue).TotalMinutes / 15 into f
from c in f
select new { StartTime = DateTime.MinValue + TimeSpan.FromMinutes(c.Key),
             Items = ... };

修正:DateTime.Now将导致问题:)

Fixed: DateTime.Now will cause issues :)

错误通知:不使用LINQ2SQL

Bug notice: Wont work with LINQ2SQL

修复:留给读者:)

这篇关于如何使用LINQ按照C#中的特定时间戳记进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆