1

我有一个包含 60 个DateTime对象的列表(按升序排序),并且需要验证每个日期是否比列表中的前一个日期大 1 个月。

例如,以下日期列表将是有效的,因为它们以一个月为增量而没有丢失:

2009 年 1 月 2009 年
2 月 2009 年
3 月 2009 年
4 月

但是,由于缺少 2009 年 2 月,以下日期列表将无效:

2009 年 1 月 2009 年
3 月 2009 年
4 月

日期无关紧要,只考虑月份年份

有没有一种有效/漂亮的方法来做到这一点?

4

4 回答 4

8

对于所有日期,如果您采用 (year * 12 + month),您将获得一个连续的整数列表。这可能更容易检查差距。

于 2009-08-06T19:55:32.923 回答
3

您可以尝试以下方法:

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);

这会将日期列表“转换”为代表年和月的数字,对于列表中的每个项目,该数字应递增 1。然后我们从这些项目中的每一个中减去当前索引,因此对于一个有效的列表,所有项目都将具有相同的值。然后我们将所有值与 进行比较start,这是第一个计算值。

于 2009-08-06T19:59:40.257 回答
1

这是一个干净的检查,使用精心设计的选择器,可以为您的用例正确比较:

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);

使用这个自定义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);
}
于 2009-08-06T20:11:52.477 回答
0
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;
}
于 2009-08-06T19:58:11.247 回答