Sil*_*fir 5 c# linq linq-to-sql
我有一些对象,测量值从这些对象保存到单个表中。我想找出一个对象在一段时间内处于某种状态的时间。
因此,除了获得具有所需状态的记录之外,我还需要将其与下一个从同一对象进行的测量配对,以计算它们之间的时间。
我想出了这个怪物:
// 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 });
Run Code Online (Sandbox Code Playgroud)
我想说这似乎不是很有效,尤其是当我使用Compact Edition 3.5时。
有什么方法可以通过m导航到下一个测量值,或者我可以某种方式使用orderby或group来通过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
});
Run Code Online (Sandbox Code Playgroud)
编辑:上面的代码并不完全等同于您的代码,因为它在配对项目之前应用过滤器。确切的优化等效将是这样的:
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');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
561 次 |
| 最近记录: |