Author Topic: Sort a list from left to right, top to bottom (in standard reading ordering)  (Read 2953 times)

0 Members and 1 Guest are viewing this topic.

nobody

  • Swamp Rat
  • Posts: 861
  • .net stuff
I'm having a heck of a time getting this right.  I tried on stackoverflow but no luck.
I am trying to sort a point collection in reading order.  Basically I have the center coordinates for rectangles (centroids) in the image shown. I think the x's and y's being the same for several of them is complicating things.  Any ideas on how I can fix my attempt below?

Code - C#: [Select]
  1. mypointlist = mypointlist.OrderByDescending(pnt => pnt.Y).ThenBy(pnt => pnt.X).ToList();


gile

  • Gator
  • Posts: 2507
  • Marseille, France
Hi,

I don't see anything wrong in the code you posted (at least the algorythm part).
Maybe an accuracy issue, try rounding the coordinates:

Code - C#: [Select]
  1. mypointlist = mypointlist.OrderByDescending(pnt => math.Round(pnt.Y, 9)).ThenBy(pnt => Math.Round(pnt.X, 9)).ToList();

Assuming mypointlist type is List<Point3d> you can also use the List<T>.Sort() method (C# 6):

Code - C#: [Select]
  1. using static System.Math;
  2. // ...
  3. mypointlist.Sort((p1, p2) =>
  4.     Round(p1.Y, 9) == Round(p2.Y, 9) ?
  5.     Round(p1.X, 9).CompareTo(Round(p2.X, 9)) :
  6.     Round(p2.Y, 9).CompareTo(Round(p1.Y, 9)));
Speaking English as a French Frog

nobody

  • Swamp Rat
  • Posts: 861
  • .net stuff
Thanks Giles...I'll give this a shot :)

Hi,

I don't see anything wrong in the code you posted (at least the algorythm part).
Maybe an accuracy issue, try rounding the coordinates:

Code - C#: [Select]
  1. mypointlist = mypointlist.OrderByDescending(pnt => math.Round(pnt.Y, 9)).ThenBy(pnt => Math.Round(pnt.X, 9)).ToList();

Assuming mypointlist type is List<Point3d> you can also use the List<T>.Sort() method (C# 6):

Code - C#: [Select]
  1. using static System.Math;
  2. // ...
  3. mypointlist.Sort((p1, p2) =>
  4.     Round(p1.Y, 9) == Round(p2.Y, 9) ?
  5.     Round(p1.X, 9).CompareTo(Round(p2.X, 9)) :
  6.     Round(p2.Y, 9).CompareTo(Round(p1.Y, 9)));

nobody

  • Swamp Rat
  • Posts: 861
  • .net stuff
You nailed it Giles, that was the problem. Can't thank you enough.

Hi,

I don't see anything wrong in the code you posted (at least the algorythm part).
Maybe an accuracy issue, try rounding the coordinates:

Code - C#: [Select]
  1. mypointlist = mypointlist.OrderByDescending(pnt => math.Round(pnt.Y, 9)).ThenBy(pnt => Math.Round(pnt.X, 9)).ToList();

Assuming mypointlist type is List<Point3d> you can also use the List<T>.Sort() method (C# 6):

Code - C#: [Select]
  1. using static System.Math;
  2. // ...
  3. mypointlist.Sort((p1, p2) =>
  4.     Round(p1.Y, 9) == Round(p2.Y, 9) ?
  5.     Round(p1.X, 9).CompareTo(Round(p2.X, 9)) :
  6.     Round(p2.Y, 9).CompareTo(Round(p1.Y, 9)));