我有一个包含 50 个元素的点列表,我想对它们进行排序,所以我使用了 orderby thenby to,但我的输出似乎是错误的。第一个元素相应地排序,但接下来的元素是错误的,这是一个屏幕截图。
正确排序的前五个数据应该与其他数据相同。但接下来的不是。我不知道是什么问题。
所以接下来的五个输出一定是:
{X=249, Y=198}
{X=249, Y=308}
{X=249, Y=413}
{X=249, Y=519}
{X=249, Y=629}
我的列表是 PointF 列表:
List<PointF> points = new List<PointF>();
这是我的代码:
points = points.OrderBy(c => c.X).ThenBy(c => c.Y).ToList();
最佳答案
请确认您的点的 X 值确实相等。我假设 249
和 249.000001
可能会在列表框中呈现为“249”,但出于排序目的不会相等。
我建议将您的代码更改为
points = points.OrderBy(c => Math.Round(c.X)).ThenBy(c => c.Y).ToList();
看看问题是否解决了。
更新:如果您的坐标预计为非整数,请切换到与指定精度进行比较:
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();
此外,您可以使用 (int)c.X
而不是使用 Round(c.X)
,因为您的评论表明这就是您将值输出到列表框的方式。
关于c# - OrderBy().ThenBy() 错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21154029/