【问题标题】:LINQ to ObjectsLINQ 到对象
【发布时间】:2013-04-24 09:05:24
【问题描述】:

我有一个基于 XML 模式构建的对象,并希望使用 LINQ 从中获取数据 我感兴趣的:)

结构类似于以下示例:

SimulationStep [1..n]
   - EnvironmentStep [1]
       - Events [0..n]
           - ResultingStateChanges [0..n]
               - Objects [1]
                   - Object[0..n]

每个“对象”(该类链中的最后一个)都有一个属性 x、y 和 z,表示该对象的位置 在 3D 空间中。还有一个 ID 用于标识每个对象。

现在我想为等于给定 ID 的对象收集每个 SimulationStep 的所有 (x,y,z) 三元组。

我试过这样:

for (int i = 0; i < stepCount; i++)
{
    var events = from c in log.SimulationStep[i].EnvironmentSimulatorStep.EnvSimInputEvent
                        from d in c.ResultingStateChanges
                        from e in d.Agents.Agent
                       where e.id == id
                       select new { c.occurrenceTime, o = new Vector3((float)e.x, (float)e.y, (float)e.z) }
}

但我得到的只是 SimulationStep 0 的结果 (x,y,z)。但我想要一个包含位置的列表 在每一步。这边走 : 比如……

SimStep[0] - (0,0,0)
SimStep[1] - (5,0,0)
SimStep[2] - (10, 7, 0)

【问题讨论】:

  • 为什么不用 XDocument 它可以让你查询 XML 数据
  • @VincentDagpin:但我现在在 LINQ。
  • @Sandy 有一个Linq2XML
  • @Aron:我没有太多经验。
  • 同样从一个非常高的层次来看,没有真正看到你的代码,它看起来是一个Access to Modified Closure 问题。在将 for 循环与 LinQ 混合时,需要非常小心。

标签: c# .net linq linq-to-objects


【解决方案1】:

希望我有你的问题。

试试这个:

//代码

var events = from s in log.SimulationStep
                        from c in s.EnvironmentSimulatorStep.EnvSimInputEvent
                        from d in c.ResultingStateChanges
                        from e in d.Agents.Agent
                        where e.id == id
                        select new { 
                                     c.occurrenceTime, 
                                     o = new Vector3((float)e.x, 
                                     (float)e.y, 
                                     (float)e.z) 
                                    }

【讨论】:

  • 假设 log.SimulationStep 公开 IEnumerable 那么这就是我要走的路。
【解决方案2】:

没有实际看到代码,我不知道 log.SimulationStep 是什么类型。如果确实是 Access Closure Modified 问题,解决这个问题的方法是简单地将 for 循环滚动到我们的 LinQ 语句中(或一直使用 for 循环)。

var events = from i in Enumerable.Range(0, stepCount)
             let simulationStep = log.SimulationStep[i]
             from c in simulationStep.EnvironmentSimulatorStep.EnvSimInputEvent
             from d in c.ResultingStateChanges
             from e in d.Agents.Agent
             where e.id == id
             select new { 
                          c.occurrenceTime, 
                          o = new Vector3((float)e.x, 
                          (float)e.y, 
                          (float)e.z) 
                        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多