2014-02-14 110 views
0

的操作,我有以下功能寻找总金额在LINQ

bool VertexOrderIsClockwise(Vector3[] vertices) { 
    float sumOverEdges = 0; 
    int vertCount = vertices.Count(); 
    for(int i = 0; i < vertCount; i++) 
     sumOverEdges += (vertices[(i+1) % vertCount].x - vertices[i].x) * (vertices[(i+1) % vertCount].z + vertices[i].z); 
    return (sumOverEdges >= 0); 
} 

林深信,使用LINQ我可以大大减少这种功能足迹。

这里是我的尝试:

bool VertexOrderIsClockwise(Vector3[] vertices) { 
    float sumOverEdges = vertices.Aggregate((current,next) => (next.x - current.x) * (next.z + current.z)); 
    return (sumOverEdges >= 0); 
} 

因此,有几件事情不对的,首先是集合函数要返回的Vector3而不是浮动(我的计算的总和) 。第二个是我无法弄清楚如何指示我的聚合在最后一次迭代中回到序列的开始。 (在我原来的功能中,我使用了%)。这可能吗?

另外我没有设置使用聚合,如果有更好的linq功能,将工作。

回答

1
return vertices.Zip(
     vertices.Skip(1) 
      .Concat(vertices.Take(1)), 
     (i,j) => (j.x - i.x) * (j.z + i.z)) 
     .Sum() >= 0;