C# sort points along line


I’m writing C# script in grasshopper. I want to sort points along polyline and create new polyline that goes trough sorted points. I came up with following code:

    Point3d[] sort_pts= culled_pts;
    double[] angles = new double[sort_pts.Length];
    for (int i = 0; i < sort_pts.Length; i++)
      angles[i] = Math.Atan2(sort_pts[i].Y, sort_pts[i].X);
    Array.Sort(angles, sort_pts);
    List<Point3d> final_pts = new List<Point3d>(sort_pts);
    Polyline final_top_poly = new Polyline(final_pts);

The problem is, that if the points Y coordinates are all 0 it breaks and doesnt work. It works if X coordinates are 0 and the rest of combination of coordinates… Any ideas why?
I appreciate the help, thanks.


Atan2 gives the angle between a “ray” on the XY Plane and the postive X axis according to wikipedia, so you could branch your code when Atan2 returns 0 (that happens when the X axis and the Point coincide), or even better, test the condition when the x component of the point is within the threshold that would return 0 when computing the Atan2 to save CPU cycles and only sort according to the X value as it will always be increasing in the positive Real values.

double threshold = 0.1;
Point3d pt = sort_pts[i];
if( pt.X < threshold && pt.X > -threshold )

     angles[i] = pt.X;


*Disclaimer I haven’t tested this code but it will solve the case that’s not working, but I think that you may have to use a different array for this case as probably the Array.Sort method may do funky things with the different logics.