Split date range into date range chunks

前端 未结 6 1306
温柔的废话
温柔的废话 2020-12-06 05:05

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 th

6条回答
  •  失恋的感觉
    2020-12-06 05:19

    Your code looks fine for me. I don't really like the idea of while(true)
    But other solution would be to use enumerable.Range:

    public static IEnumerable> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
    {
        return Enumerable
              .Range(0, (Convert.ToInt32((end - start).TotalDays) / dayChunkSize +1))
              .Select(x => Tuple.Create(start.AddDays(dayChunkSize * (x)), start.AddDays(dayChunkSize * (x + 1)) > end
                                                                           ? end : start.AddDays(dayChunkSize * (x + 1))));
    }  
    

    or also, this will also work:

    public static IEnumerable> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
    {
        var dateCount = (end - start).TotalDays / 5;
        for (int i = 0; i < dateCount; i++)
        {
            yield return Tuple.Create(start.AddDays(dayChunkSize * i)
                                    , start.AddDays(dayChunkSize * (i + 1)) > end 
                                     ? end : start.AddDays(dayChunkSize * (i + 1)));
        }
    }
    

    I do not have any objects for any of the implementations. They are practically identical.

提交回复
热议问题