简体   繁体   中英

Finding the aggregate sum an operation in linq

I have the following function

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

Im convinced that using linq I can drastically reduce this functions footprint.

Here is my attempt:

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

So there is a few things wrong with this, the first is that the aggregate function wants to return a Vector3 and not a float (The total sum of my calculations). The second is that I cant figure out how to instruct my aggregate to wrap around to the beginning of the sequence on the last iteration. (In my original function I used a %). Is this possible?

Also Im not set on using aggregate if there is a better linq function that will work.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM