比较列表中的点

Adr*_*rao 0 .net c# winforms

我有一个简单的点列表List<Point>,我用鼠标填充.就像,当我单击鼠标时,该位置将添加到列表中.问题是新位置添加在列表的底部.我想要做的是,当我单击鼠标时,搜索列表中的所有现有点并将最近的点返回到鼠标位置,然后在该点之后插入新点.

我一直在网上搜索几个小时,我似乎无法找到解决方案.任何帮助将不胜感激.谢谢!

Dav*_*vid 5

List<>类包含.Insert()方法来做到这一点.当您搜索列表并找到"最近"元素(但是您定义该逻辑)时,您可以在列表中获取对象的索引.然后在该索引之后插入新的.就像是:

var closestPoint = FindClosestPoint(listOfPoints, newPoint);
var index = listOfPoints.IndexOf(closestPoint);
listOfPoints.Insert(index + 1, newPoint);
Run Code Online (Sandbox Code Playgroud)

获得最接近的点应该是几何的简单问题.平面上有两个X/Y坐标.它们之间的距离是轴的平方和的平方根.所以你只需要那个值最小的元素.像这样的东西:

var closestPoint = listOfPoints
                   .Select(p => new {
                       Point = p,
                       Distance = Math.Sqrt(
                           Math.Pow(Math.Abs(p.X - closestPoint.X), 2) +
                           Math.Pow(Math.Abs(p.Y - closestPoint.Y), 2)
                       )
                   })
                   .OrderByDesc(p => p.Distance)
                   .First();
Run Code Online (Sandbox Code Playgroud)