Jer*_*oyd 1 c# datetime out-of-memory
这可能是一个简单的修复,但我不能为我的生活想到如何做到这一点.我使用此查询将一堆StartDates和End Dates计算到一堆日期数组中:
this.Reserved = unit.Reservations.Where(r => r.Active.HasValue && r.Active.Value).SelectMany(r => Utilities.DateRangeToArray(r.StartDate, r.EndDate)).ToArray();
Run Code Online (Sandbox Code Playgroud)
Utilities.DateRangeToArray()定义如下:
public static IEnumerable<DateTime> DateRangeToArray(DateTime start, DateTime end) {
DateTime curDate = start;
while (curDate <= end) {
yield return curDate;
curDate.AddDays(1);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法减少内存密集?
谢谢!
您的代码已损坏 - AddDays不会更改现有值,而是返回新值.你忽略了这个新值,从而创造了一个无限循环.
将您的代码更改为:
public static IEnumerable<DateTime> DateRangeToArray(DateTime start,
DateTime end) {
DateTime curDate = start;
while (curDate <= end) {
yield return curDate;
curDate = curDate.AddDays(1);
}
}
Run Code Online (Sandbox Code Playgroud)
另一个提示:在您尝试在LINQ查询中使用该方法之前,单元测试可以帮助您找到此类问题.我也会更改名称,因为它没有返回数组.
| 归档时间: |
|
| 查看次数: |
513 次 |
| 最近记录: |