Skip to content

Instantly share code, notes, and snippets.

@leandromoh
Created September 10, 2024 17:29
Show Gist options
  • Save leandromoh/4cd3ad29c0bdb69265314553ee01d6bf to your computer and use it in GitHub Desktop.
Save leandromoh/4cd3ad29c0bdb69265314553ee01d6bf to your computer and use it in GitHub Desktop.
group values by time.cs
using System;
using System.Collections.Generic;
using System.Linq;
var series = new List<Sample>();
series.Add(new (){ timestamp = DateTime.Now.AddMinutes(-3) });
series.Add(new (){ timestamp = DateTime.Now.AddMinutes(0) });
series.Add(new (){ timestamp = DateTime.Now.AddMinutes(3) });
series.Add(new (){ timestamp = DateTime.Now.AddMinutes(4) });
series.Add(new (){ timestamp = DateTime.Now.AddMinutes(5) });
series.Add(new (){ timestamp = DateTime.Now.AddMinutes(6) });
series.Add(new (){ timestamp = DateTime.Now.AddMinutes(7) });
series.Add(new (){ timestamp = DateTime.Now.AddMinutes(15) });
var groups = series.GroupBy(x =>
{
var ticks = TimeSpan.FromMinutes(5).Ticks;
var stamp = x.timestamp.Ticks % ticks;
return x.timestamp.AddTicks(-stamp + ticks);
})
.ToList();
foreach(var g in groups)
{
Console.WriteLine(g.Key);
foreach(var x in g)
{
Console.WriteLine(x);
}
Console.WriteLine();
}
public record class Sample
{
public DateTime timestamp;
}
@leandromoh
Copy link
Author

output

09/10/2024 17:30:00
Sample { timestamp = 09/10/2024 17:28:05 }

09/10/2024 17:35:00
Sample { timestamp = 09/10/2024 17:31:05 }
Sample { timestamp = 09/10/2024 17:34:05 }

09/10/2024 17:40:00
Sample { timestamp = 09/10/2024 17:35:05 }
Sample { timestamp = 09/10/2024 17:36:05 }
Sample { timestamp = 09/10/2024 17:37:05 }
Sample { timestamp = 09/10/2024 17:38:05 }

09/10/2024 17:50:00
Sample { timestamp = 09/10/2024 17:46:05 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment