问题描述
我正在努力实现算法。
我有一个开始日期和一个结束日期,我想列出该时间跨度内所有可能的时间跨度,并使用特殊条件作为开始和结束日期。
例如:
我的开始日期是 01-01-2020
,我的结束日期是 31-01-2020
。我的条件是列出至少有 7 days
和最大 10 days
的所有可能的时间跨度。
所以结果集应该是这样的:
01-01-2020 -> 08-01-2020
01-01-2020 -> 09-01-2020
...
02-01-2020 -> 09-01-2020
...
24-01-2020 -> 31-01-2020
最好是 Linq,所以我可以列举。
解决方法
这是一个简单的实现。这不是最有效的,但很容易理解:
public static IEnumerable<(DateTime start,DateTime end)> ListTimespans(DateTime startDate,DateTime endDate,int minDays,int maxDays)
{
// Loop through all of the possible starts. The first day we can start on is startDate,// and the last day we can start on is endDate - minDays (which gives us a span
// minDays long ending on endDate)
for (var start = startDate; start <= endDate.AddDays(-minDays); start = start.AddDays(1))
{
// For each of these starts,loop through the possible end dates. There are two
// limits to the end date: either hit the maximum number of days for a span
// (start.AddDays(maxDays)),or we hit the end date.
// Loop until whichever one comes first.
for (var end = start.AddDays(minDays); end <= Min(start.AddDays(maxDays),endDate); end = end.AddDays(1))
{
yield return (start,end);
}
}
DateTime Min(DateTime x,DateTime y) => x < y ? x : y;
}
查看实际操作here。