Sort points in optional coordinates

Hi I tried using the method Sort() for sorting a bunch of points but it first attempts to sort points in x direction , then in y and at last in z . my intention would be to sort them optionally (e.g. first z , then x , then y). Any tips ?

Using Array.Sort() method uses default comparer for particular type. For Point3D it works exactly as you describe. But you can create you own comparer and call Sort() method with that comparer so sorting can be whatever you write in your code.
In attached code is example of sorting points by Y, Z and along arbitrary vector. (10.8 KB)

1 Like

I’m totally okay with sorting along one axis but when I attempt to sort them in 2 or 3 coordinates simultaneously it fails and just sort it in one direction . my desired sort would be like .Sort(); but to change what coordinates be sorted first .

Simplest would be to use LINQ that lets you do it in one line of code:

sortedPoints = points.OrderBy(i => i.Z).ThenBy(j => j.X).ThenBy(k => k.Y); (5.6 KB)

As Nathan said it is simple task if u use LINQ.

If you want objects (points) to be sorted in any other specific way you will have to write your Comparer.
In code attached there is example for:

  • comparer for sorting points in YZX order (fist compare Y, if equal then compare Z, if still equal compare X).
  • comparer for sorting along line (vector with anchor point) and if two points lies on the same perpendicular plane additional comparison is perform on distance btw points and line, closest point to the line will be “smaller” (12.1 KB)