Reputation: 510
I have a simple list of points List<Point>
which I populate using the mouse. Like, when I click the mouse, the location is added into the list. The problem is that the new location is added at the bottom of the list. What I want to do is, when I click the mouse, search all the existing points in the list and return the closest point to the mouse location, and insert the new point after that one.
I've been searching the web for hours and I can't seem to find a solution. Any help will be appreciated. Thanks!
Upvotes: 0
Views: 799
Reputation: 218877
The List<>
class contains an .Insert()
method to do just that. When you search the list and find the "closest" element (however you define that logic), you can get the index of that object in the list. Then just insert the new one after that index. Something like:
var closestPoint = FindClosestPoint(listOfPoints, newPoint);
var index = listOfPoints.IndexOf(closestPoint);
listOfPoints.Insert(index + 1, newPoint);
Getting the closest point itself should be a simple matter of geometry. You have two X/Y coordinates on a plane. The distance between them is the square root of the sum of the squares of the axes. So you just need the element where that value is the smallest. Something like this:
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();
Upvotes: 5