title: In C#, What is the best way to aggregate and transform one DateTime collection into another?
body: <p>I have a little calendar tool in C# and I am trying to figure out how to do a conversion from one array of DateTime objects to another.  Here are the details:</p>
  
  <p>I start off with collection of DateTime object</p>
  
  <pre><code> IEnumerable&lt;DateTime&gt; slots = GetSlots();
  </code></pre>
  
  <p>where each DateTime represents that starting time of an available slot (think open slot in calendar) <strong>All slots are for 30 minutes</strong> This is a given.  So for example:</p>
  
  <pre><code>var slots = new List&lt;DateTime&gt;()
  
  slots.Add(DateTime.Today + new TimeSpan(5,00, 0));
  
  slots.Add(DateTime.Today + new TimeSpan(9,00, 0));
  slots.Add(DateTime.Today + new TimeSpan(9,30, 0));
  slots.Add(DateTime.Today + new TimeSpan(10,00, 0));
  slots.Add(DateTime.Today + new TimeSpan(10,30, 0));
  slots.Add(DateTime.Today + new TimeSpan(11,00, 0));
  slots.Add(DateTime.Today + new TimeSpan(16,30, 0));
  </code></pre>
  
  <p>in the above example, it means i am free:</p>
  
  <ol>
  <li>From 5:00 - 5:30</li>
  <li>From 9:00 - 9:30</li>
  <li>From 9:30 - 10:00</li>
  <li>From 10:00 - 10:30</li>
  <li>From 10:30 - 11:00</li>
  <li>From 11:00 - 11:30</li>
  <li>From 4:30 - 5:00</li>
  </ol>
  
  <p>because i take the time from the item in the collection as the start time and simply add 30 minutes to it and that is considered a free slot.</p>
  
  <p>I now have the requirement to take a larger time window (lets use 2 hours) and find out how many 2 hour slots free i have so  I now need to take this array of dates and "merge" into into bigger buckets. Given the bigger bucket is 2 hours (120 minutes), I want a function like this</p>
  
  <pre><code>IEnumerable&lt;DateTime&gt; aggregateArray = MergeIntoLargerSlots(slots, 120);
  </code></pre>
  
  <p>I would basically have to loop through the slots array above and "merge" items that are lined up next to each out to make bigger buckets.  If any of the merged items is 2 hours long then that should show up as an entry in the resulting array.  Using the example above the resulting aggregateArray would have 2 items in the collection it that would have the times:</p>
  
  <ul>
  <li>9AM (because i have a free slot from 9-11 AM (120 mins). </li>
  <li>9:30AM (because i have a free slot from 9:30-11:30 AM (120 mins). </li>
  </ul>
  
  <p><em>NOTE:</em> 30 minutes "chunks" are the smallest interval so DON'T need to include 9:05 to 11:05 as an example</p>
  
  <p>So given the previous array I have two 2 hour windows of time free in the day</p>
  
  <p>I am struggling to figure out how this MergeIntoLargerSlots function would work so i would hoping to get some suggestion for how to approach this problem.</p>