Linq-查询之前比较记录 [英] Linq - Query compare to record before

查看:70
本文介绍了Linq-查询之前比较记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此查询查看其之前的记录,并减去时间以计算总时间.但是,当对第一条记录求值时,它会在减去后在第三行上引发错误.索引超出范围.当我删除Sum()时,错误消失了,但是我需要有效地求和.

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();

还有什么我想念的吗?

推荐答案

上面的查询存在的问题是,当您到达具有最小EndTime的项目时,什么都找不到,结果为空.然后,您尝试获取导致错误的空集合的最大值.

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);

这篇关于Linq-查询之前比较记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆