This query looks at the record before it and subtr开发者_开发技巧acts the times to calculate the total amount of time. However, when the first record is evaluated it throws an error on the third line after the subtraction. Index out of bounds. When I remove the Sum() then the error goes away, but I need the sum efficiently.
var allRecorded = queryable.Where(x => x.DataId== Id);
var dataFiltered = allRecorded.Where(x => x.DataValue >= lowerThreshold && x.DataValue < upperThreshold);
var sumOfExactTimes = dataFiltered.Select(times => (times.EndTime - allRecorded.Where(time2 => time2.EndTime < times.EndTime).Select(x => (DateTime?) x.EndTime).Max()).GetValueOrDefault().TotalMinutes).Sum();
Is there anything else I'm missing?
The problem with the query you have above is that when you reach the item with the minimum EndTime
, nothing is found giving you an empty result. You then try to take the maximum of an empty collection which causes the error.
However this query could be simplified tremendously. It would be easier to sort it first then aggregate to find the differences.
var data = queryable
.Where(item => item.DataId == id
&& item.DataValue >= lowerThreshold
&& item.DataValue < upperThreshold)
.OrderBy(item => item.EndTime)
.ToList();
var sumOfExactTimes = data.Skip(1)
.Aggregate(
Tuple.Create(data.First(), 0.0), // [1] Prev Item [2] Result
(seed, item) =>
Tuple.Create(
item,
seed.Item2 + (item.EndTime - seed.Item1.EndTime).TotalMinutes),
result => result.Item2);
精彩评论