C# 列出时间跨度内所有可能时间跨度的算法
我正在为一个算法实现而苦苦挣扎 我有一个开始日期和一个结束日期,我想列出该时间跨度内所有可能的时间跨度,并以特殊条件作为开始日期和结束日期 例如: 我的开始日期是C# 列出时间跨度内所有可能时间跨度的算法,c#,algorithm,linq,datetime,timespan,C#,Algorithm,Linq,Datetime,Timespan,我正在为一个算法实现而苦苦挣扎 我有一个开始日期和一个结束日期,我想列出该时间跨度内所有可能的时间跨度,并以特殊条件作为开始日期和结束日期 例如: 我的开始日期是01-01-2020,我的结束日期是31-01-2020。我的条件是列出所有可能的时间跨度,这些时间跨度至少为7天,最长为10天 因此,结果集如下所示: 01-01-2020 -> 08-01-2020 01-01-2020 -> 09-01-2020 ... 02-01-2020 -> 09-01-2020 ...
01-01-2020
,我的结束日期是31-01-2020
。我的条件是列出所有可能的时间跨度,这些时间跨度至少为7天
,最长为10天
因此,结果集如下所示:
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;
}
公共静态IEnumerable ListTimespans(DateTime startDate、DateTime endDate、int minDays、int maxDays)
{
//循环所有可能的开始。我们可以开始的第一天是startDate,
//我们可以开始的最后一天是endDate-minDays(这给了我们一个跨度)
//minDays(在endDate结束)
对于(var start=startDate;start