开发者

System.OutOfMemoryException thrown when computing date ranges

It might be a simple fix, but I can't for the life of me think of how to do this. I compute a bunch of StartDates and End Dates into a bunch of arrays of dates using this query:

this.Reserved = unit.Reservations.Where(r => r.Active.HasValue && r.Active.Value).SelectMany(r => Utilities.DateRangeToArray(r.StartDate, r.EndDate)).ToArray();

Utilities.DateRangeToArray() is defined 开发者_JAVA技巧as follows:

public static IEnumerable<DateTime> DateRangeToArray(DateTime start, DateTime end) {
    DateTime curDate = start;
    while (curDate <= end) {
        yield return curDate;
        curDate.AddDays(1);
    }
}

Is there a way to make this less memory intensive?

Thanks!


Your code is broken - AddDays doesn't change the existing value, it returns a new value. You're ignoring that new value, thus creating an infinite loop.

Change your code to:

public static IEnumerable<DateTime> DateRangeToArray(DateTime start,
                                                     DateTime end) {
    DateTime curDate = start;
    while (curDate <= end) {
        yield return curDate;
        curDate = curDate.AddDays(1);
    }
}

Another hint: unit testing can help you find this sort of problem long before you try to use the method in a LINQ query. I'd also change the name, given that it's not returning an array.


You're sure you don't have any reservations where r.StartDate > r.EndDate, right? If you do, you'll get an infinite loop, I think.


I assume the out of memory is when converting the result to the array. Two points:

  • The output will contain duplicate dates for overlapping reservations.
  • Perhaps Reserved should be a collection of date ranges (start,end) rather than containing every date?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜