tags:

views:

169

answers:

2

Hi

Given a list of dates (which may not be sorted), I want to build a list of date ranges -

E.g. Assuming MM/DD format,

Input - 5/1, 5/5, 5/6, 5/15, 5/7, 5/8, 5/19,5/20, 5/23

Output -

Date Range 1: 5/1 to 5/1
Date Range 2: 5/5 to 5/8
Date Range 3: 5/15 to 5/15
Date Range 4: 5/19 to 5/20
Date Range 5: 5/23 to 5/23

Basically, a range should be continuous.

Thanks

Nakul Ringshia

A: 

You can create a list of DateTime (possibly using the same year for them all) and sort it.

It is then fairly easy to find if a day and the next day exist in the list (using DateTime.AddDays(1)).

Oded
+3  A: 
  1. Sort the dates
  2. Start a range containing the next date (to start with it will be the first one)
  3. Is the second "valid" date the next date which would be in the range? If so, keep going. If not, close the current range and start a new one.
  4. Repeat until you've run out of dates, at which point you close the current range and you're done.
Jon Skeet