Skip to content

Instantly share code, notes, and snippets.

@vkobel
Created October 9, 2014 11:24
Show Gist options
  • Save vkobel/1dcaebf062e856984f65 to your computer and use it in GitHub Desktop.
Save vkobel/1dcaebf062e856984f65 to your computer and use it in GitHub Desktop.
Group datetimes by duration. Here it will make 3 groups of 15 minutes each
using System;
using System.Linq;
namespace GroupbyTimespan {
class Program {
static void Main(string[] args) {
DateTime[] dateTimes = new[]{
new DateTime(2010, 8, 24, 0, 5, 0),
new DateTime(2010, 8, 24, 0, 10, 0),
new DateTime(2010, 8, 24, 0, 15, 0),
new DateTime(2010, 8, 24, 0, 20, 0),
new DateTime(2010, 8, 24, 0, 25, 0),
new DateTime(2010, 8, 24, 0, 30, 0)
};
TimeSpan interval = new TimeSpan(0, 15, 0);
var groupedTimes = from dt in dateTimes
group dt by dt.Ticks / interval.Ticks
into g
select new { Begin = new DateTime(g.Key * interval.Ticks), Values = g.ToList() };
foreach(var value in groupedTimes) {
Console.WriteLine(value.Begin);
Console.WriteLine("\t{0}", String.Join(", ", value.Values));
}
Console.ReadLine();
}
}
}
24.08.2010 00:00:00
24.08.2010 00:05:00, 24.08.2010 00:10:00
24.08.2010 00:15:00
24.08.2010 00:15:00, 24.08.2010 00:20:00, 24.08.2010 00:25:00
24.08.2010 00:30:00
24.08.2010 00:30:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment