OrderBy().ThenBy()输出错误

jul*_*ion 5 c# linq sorting list point

我有一个包含50个元素的点列表,我想对它们进行排序,所以我使用了orderby然后,但我的输出似乎是错误的.第一个元素相应地排序,但下一个元素是错误的,这是一个屏幕截图.

在此输入图像描述

正确排序的前五个数据应该是其他数据的数据.但接下来的不是.我不知道是什么问题.

所以接下来的五个输出必须是:

{X=249, Y=198}

{X=249, Y=308}

{X=249, Y=413}

{X=249, Y=519}

{X=249, Y=629}
Run Code Online (Sandbox Code Playgroud)

我的列表是PointF列表:

List<PointF> points = new List<PointF>();
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

points = points.OrderBy(c => c.X).ThenBy(c => c.Y).ToList();
Run Code Online (Sandbox Code Playgroud)

Zru*_*uty 6

请确认您的积分的X值确实相等.我认为两者249并249.000001可能会呈现为一个列表框"249",但将不等于对订货的目的.

我建议你改变你的代码

points = points.OrderBy(c => Math.Round(c.X)).ThenBy(c => c.Y).ToList();
Run Code Online (Sandbox Code Playgroud)

并看看问题是否已经消失.

更新:如果您的坐标预期为非整数,请切换到与指定精度进行比较:

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();
Run Code Online (Sandbox Code Playgroud)

此外,Round(c.X)您可以使用,而不是使用(int)c.X,因为您的注释表明这是您将值输出到列表框的方式.