Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderBy().ThenBy() wrong output

I have a list of Points with 50 elements, I wanted to sort them so I used orderby thenby to, but my output seems to be wrong. The first elements are sorted in accordingly, but the next ones are wrong, here is a screen shot.

enter image description here

The 1st five data where sorted correctly, that should be what the other data would be. but the next ones are not. I don't know what is the problem.

So the next five output must be:

{X=249, Y=198}

{X=249, Y=308}

{X=249, Y=413}

{X=249, Y=519}

{X=249, Y=629}

My list is a PointF list:

List<PointF> points = new List<PointF>();

Here is my code:

points = points.OrderBy(c => c.X).ThenBy(c => c.Y).ToList();
like image 583
julianconcepcion Avatar asked Jan 16 '14 05:01

julianconcepcion


1 Answers

Please verify that your points' X values are indeed equal. I assume both 249 and 249.000001 may get rendered as "249" in a listbox, but will not be equal for the ordering purposes.

I suggest changing your code to

points = points.OrderBy(c => Math.Round(c.X)).ThenBy(c => c.Y).ToList();

and seeing if the problem is gone.

UPDATE: if your coordinates are expected to be non-integers, switch to comparing with specified precision:

var precision = 0.001; // choose the value that suits you. If the tow values are different by less than this amount, the values are considered equal.
points = points.OrderBy(c => Math.Round(c.X / precision)).ThenBy(c => c.Y).ToList();

Also, instead of using Round(c.X) you could use (int)c.X, since your comments indicate that this is how you output your values to the listbox.

like image 146
Zruty Avatar answered Oct 08 '22 02:10

Zruty