LINQ select 每个匹配结果的下一条记录

LINQ select next record with each matching result

我有一些对象,其中的测量值被保存到单个 table。我想知道一个对象在一段时间内处于某种状态的时间。

因此,除了获得具有所需状态的记录外,我还需要将其与对同一对象进行的下一次测量配对,以计算它们之间的时间。

我想到了这个怪物:

// Get the the object entry from Database
MeasuredObject object1;
try
{
   object1 = (MeasuredObject)(from getObject in db.MeasuredObject where wantedObject.Id.Equals(getObject.Id) select getObject).Single();
}
catch (System.ArgumentNullException e)
{
   throw new System.ArgumentException("Object does not exist", "wantedObject", e);
}

// Get every measurement which matches the state in the time period and the next measurement from it
var pairs = (from m in object1.Measurements
             join nextM in object1.Measurements
             on (from next in object1.Measurements where (m.Id < next.Id) select next.Id).Min() equals nextM.Id
             where 'm is in time period and has required state'
             select new { meas = m, next = nextM });

我会说这似乎不是很有效,尤其是当我使用 Compact Edition 3.5 时。

有什么方法可以通过 m 导航到下一个测量值,或者我可以以某种方式使用 orderby 或 group 到 select next by Id 吗?或者甚至让 join 子句更简单?

从发布的代码看来,您正在使用内存集合。如果这是真的,那么以下内容就足够了:

var items = (from m in object1.Measurements
             where 'm is in time period and has required state'
             orderby m.Id
             select m)
            .ToList();

var pairs = items.Select((item, index) => new
            {
                meas = item,
                next = index + 1 < items.Count ? items[index + 1] : null
            }); 

编辑: 以上与您的代码不完全相同,因为它在配对项目之前应用过滤器。确切的优化等价物是这样的:

var items = object1.Measurements.OrderBy(m => m.Id).ToList();

var pairs = items.Select((item, index) => new
            {
                meas = item,
                next = index + 1 < items.Count ? items[index + 1] : null
            })
            .Where(pair => 'pair.meas is in time period and has required state');