views:

162

answers:

4

I have a list containing 60 DateTime objects (sorted in ascending order) and need to validate that each date is 1 month greater than the previous one in the list.

For example, the following list of dates would be valid because they increment by one month with none missing:

Jan-2009
Feb-2009
Mar-2009
Apr-2009

However, the following list of dates would be invalid because Feb-2009 is missing:

Jan-2009
Mar-2009
Apr-2009

The day doesn't matter, just the month and year are considered.

Is there an efficient/pretty way of doing this?

+8  A: 

For all of the dates, if you take (year * 12 + month) you'll get a sequential list of integers. That might be easier to check for gaps.

David
+1 Simpler is better.
Bob Kaufman
A: 
public bool MonthsAreSequential(IList<DateTime> dates)
{
    if (dates.Count < 2) return true;

    for (int i = 0; i < dates.Count - 1; i++)
    {
        var plusOne = dates[i].AddMonth(1);
        var nextMonth = dates[i + 1];
        if (plusOne .Year != nextMonth .Year 
            || plusOne .Month != nextMonth .Month)
            return false;
    }
    return true;
}
Garry Shutler
Concurrent: operating or occurring at the same time; Sequential: of, relating to, or arranged in a sequence (http://www.merriam-webster.com/dictionary)
grenade
Doh, my bad. Got mixed up.
Garry Shutler
+3  A: 

You could try the following:

int start = list.First().Year * 12 + list.First().Month;
bool sequential = list
    .Select((date, index) => date.Year * 12 + date.Month - index)
    .All(val => val == start);

This 'converts' the list of dates into a number that represents the Year and Month, which should be incrementing by 1 for each item in the list. We then subtract the current index from each of those items, so for a valid list, all items would have the same value. We then compare all values to start, which is the first computed value.

Jason
+1  A: 

Here's a clean check, making use of a carefully crafted selector that will compare correctly for your use case:

IEnumerable<DateTime> dates = ...;
DateTime firstDate = dates.First();
IEnumerable desired = Enumerable.Range(0, 60).Select(months => firstDate.AddMonths(months));
bool correct = dates.SequenceEqual(desired, date => date.Year*12 + date.Month);

Using this custom SequenceEqual:

public static bool SequenceEqual<T1, T2>(this IEnumerable<T1> first, IEnumerable<T1> second, Func<T1, T2> selector)
{
    // uses the LINQ Enumerable.SequenceEqual method on the selections
    return first.Select(selector).SequenceEqual(second.Select(selector));
}

// this is also useful, but not used in this example
public static bool SequenceEqual<T1, T2>(this IEnumerable<T1> first, IEnumerable<T1> second, Func<T1, T2> selector, IEqualityComparer<T2> comparer)
{
    return first.Select(selector).SequenceEqual(second.Select(selector), comparer);
}
280Z28