我尝试过,虽然这可能不是一种非常有效的做事方式;康拉德答案中的链接似乎是一个探索的好地方。
我不完全确定你是如何定义“范围内”的,所以我假设了一个简单的距离计算。
// Set up some points
List<Point> Points = new List<Point>();
Points.Add(new Point(0, 0));
Points.Add(new Point(0, 1));
Points.Add(new Point(0, 2));
// Distance
int maxDistance = 1;
// Replace as appropriate
Func<Point, Point, int, bool> myDistanceFunction = delegate(Point p1, Point p2, int range)
{
// Same coordinate.
if (p1 == p2)
return true;
int xDelta = p1.X - p2.X;
int yDelta = p1.Y - p2.Y;
double distance = Math.Sqrt(xDelta * xDelta + yDelta * yDelta);
return (distance <= range);
};
// Loop through all points and calculate distance to all other points.
var Results = Points.Select(firstPoint => new
{
TargetPoint = firstPoint,
PointsInRange = Points
.Where(secondPoint =>
(secondPoint != firstPoint) && // Will you allow same coordinates?
myDistanceFunction(secondPoint, firstPoint, maxDistance))
});
// Spit the results out.
foreach (var result in Results)
{
Console.WriteLine("Point {0} - Points within {1} unit(s):", result.TargetPoint, maxDistance);
foreach (var point in result.PointsInRange)
{
Console.WriteLine("\t{0}", point);
}
}
输出:
Point {X=0,Y=0} - Points within 1 unit(s):
{X=0,Y=1}
Point {X=0,Y=1} - Points within 1 unit(s):
{X=0,Y=0}
{X=0,Y=2}
Point {X=0,Y=2} - Points within 1 unit(s):
{X=0,Y=1}
还有改进的余地,例如计算两次点对的距离并不明智,如果您允许重复坐标,我不会这样做,但那里可能会有用处。
你也可以将距离函数写成兰巴表达式,虽然我不确定它是否更清晰。
Func<Point, Point, int, bool> myDistanceFunction =
(
(p1, p2, range) => Math.Sqrt(
((p1.X - p2.X) * (p1.X - p2.X)) +
((p1.Y - p2.Y) * (p1.Y - p2.Y))
) <= range
);