问题描述
此查询查看它之前的记录并减去时间以计算总时间.但是,当评估第一条记录时,它会在减法后的第三行引发错误.索引超出范围.当我删除 Sum() 时,错误就会消失,但我需要有效地求和.
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();
我还有什么遗漏的吗?
推荐答案
您上面的查询的问题是,当您到达具有最小值 EndTime 的项目时,没有找到任何结果给您一个空结果.然后,您尝试获取导致错误的空集合的最大值.
但是,这个查询可以大大简化.首先对其进行排序然后汇总以查找差异会更容易.
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);
问题描述
This query looks at the record before it and subtracts 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);