Skip to content

Instantly share code, notes, and snippets.

@amithegde
Created May 1, 2014 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amithegde/fa3826733f6295b8c013 to your computer and use it in GitHub Desktop.
Save amithegde/fa3826733f6295b8c013 to your computer and use it in GitHub Desktop.
void Main()
{
//my data entities
var dataList = new List<DataModel>();
for (int i = 0; i < 100; i++) {
dataList.Add(new DataModel {
SomeString = "some data",
SomeValue = i,
Timestamp = DateTimeOffset.UtcNow.AddMinutes(-(i+60))
});
}
//my aggregation intervals, collected one hour apart
var range = new List<TimeInterval>();
var time = DateTimeOffset.UtcNow.RoundUpToHour().AddHours(+3);
for (int i = 0; i < 100; i++) {
range.Add(new TimeInterval {
Start = time.AddHours(-(i+1)),
End = time.AddHours(-(i)),
});
}
//dataList.Dump("original data");
//range.Dump("timeframe range");
//dataList.GroupBy(x => GetKey(range, x)).Select(x => new { x.Key, Val = x }).First().Dump("Gruped");
dataList.GroupBy(x => GetKey(range, x)).ToDictionary(x => x.Key).Dump();
}
private static DateTimeOffset GetKey(List<TimeInterval> rg, dynamic item)
{
//key range should cover the items always otherwise it will throw null ref exception
var t = rg.FirstOrDefault(r => r.Start <= item.Timestamp && r.End >= item.Timestamp);
return t.End;
}
public static class DateTimeOffsetHelper
{
public static DateTimeOffset RoundUpToHour(this DateTimeOffset dateTime)
{
DateTimeOffset previous = dateTime.RoundDownToHour();
//if the given date time is already an exact hour, just return it
//otherwise, add an hour to the rounded down previous hour and return that
return dateTime == previous ? dateTime : previous.AddHours(1);
}
public static DateTimeOffset RoundDownToHour(this DateTimeOffset dateTime)
{
DateTimeOffset previous = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day,
dateTime.Hour, 0, 0, dateTime.Offset);
return previous;
}
}
private class DataModel
{
public DateTimeOffset Timestamp { get; set; }
public int SomeValue { get; set; }
public string SomeString { get; set; }
}
private class TimeInterval
{
public DateTimeOffset Start { get; set; }
public DateTimeOffset End { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment