问题描述
我要寻找分裂日期范围为一系列的日期范围的天块大小的方法。我打算利用这个缓冲调用它,如果日期范围过大,服务故障的服务。
I am looking for a method of splitting a date range into a series of date ranges by chunk size of days. I am planning on using this to buffer calls to a service which if the date range is too large, the service faults.
这是我想出了这么远。它似乎工作,但我不知道这是否正常退出。这似乎喜欢的事,可能已经做过好几次,但我不能找到它。
This is what I have come up with so far. It seems to work, but I am not sure if it will exit properly. This seems like something that has probably been done several times before, but I can't find it.
public IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
var newStart = start;
var newEnd = start.AddDays(dayChunkSize);
while (true)
{
yield return new Tuple<DateTime, DateTime>(newStart, newEnd);
if (newEnd == end)
yield break;
newStart = newStart.AddDays(dayChunkSize);
newEnd = (newEnd.AddDays(dayChunkSize) > end ? end : newEnd.AddDays(dayChunkSize));
}
}
我在寻找改进的建议,或哥们,使用现有的功能,为这个!
I'm looking for improvement suggestions, or "Dude, use this existing function for this!"
推荐答案
我觉得你的code时,起点和终点之间的差值小于dayChunkSize小失败。看到这个:
I think your code fails when the difference between start and end is smaller than dayChunkSize.See this:
var singleRange = SplitDateRange(DateTime.Now, DateTime.Now.AddDays(7), dayChunkSize: 15).ToList();
Debug.Assert(singleRange.Count == 1);
建议的解决方案:
Proposed solution:
public static IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime chunkEnd;
while ((chunkEnd = start.AddDays(dayChunkSize)) < end)
{
yield return Tuple.Create(start, chunkEnd);
start = chunkEnd;
}
yield return Tuple.Create(start, end);
}
这篇关于拆分日期范围为日期范围块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!