c# - OrderBy().ThenBy() 错误输出

标签 c# linq list sorting point

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

enter image description here

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

所以接下来的五个输出一定是:

{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 值确实相等。我假设 249249.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/

相关文章:

r - 从 map 中的列表中获取对象的名称

list - Scala 根据条件在 2 个列表之间合并

c# - InspirationContext 不持久化内容

C# FakeItEasy 和方法链接 : Only First Call Is Recognized

linq - ASP.Net MVC 将 Sql 转换为 Linq

c# - 加入时在 linq 中排序

c# - asp.net core 2.0 部署 - InvalidOperationException : The antiforgery token could not be decrypted

c# - 为什么 List<T> 没有采用 params 参数的构造函数?

c# - 使用 Linq 的字典列表 <Type>

python - 将所有键值附加到字典值列表中存在的列表