在列表中查找n个最近的点

时间:2017-08-15 14:15:05

标签: c# grasshopper rhino3d

C#beginner here,使用Grasshopper for Rhino,所以有些对象类型有点奇怪。

我目前正在尝试在列表中找到给定点的n个最近点。我能够使用以下函数找到最近的点,但无法使其适应以检索多个最近的点。

public Vec3D ClosestPoint(Vec3D a, List<Vec3D>points){
  List<float> distanceList = new List<float>();
  for (int i = 0; i < points.Count(); i++){
    float distanceFloat = a.distanceTo(points[i]);
    distanceList.Add(distanceFloat);
  }
  int smallestIndex = distanceList.IndexOf(distanceList.Min());
  return points[smallestIndex];
}

我如何为下面的函数调整此代码,其中n是要找到的最近点数?

public Vec3D ClosestPoints(Vec3D a, List<Vec3D>points, int n){

  } 

1 个答案:

答案 0 :(得分:0)

您可以使用Linq获得该结果:

public IEnumerable<Vec3D> ClosestPoints(Vec3D a, List<Vec3D>points, int n) =>

  points.Select(point => new 
  { 
     point = point, 
     distance = a.distanceTo(point) 
  }).
  OrderBy(x = x.distance).
  Take(n).
  Select(x => x.point);

请注意,在这种情况下,另一种方法变为:

public Vec3D ClosestPoint(Vec3D a, List<Vec3D>points) =>
  ClosestPoints(a, points, 1).FirstOrDefault();