Skip to main content
 首页 » 编程设计

c#之获取与点相关的最小距离的列表元素

2024年02月13日11lonelyxmas

我有一个类 WorldObject。在这个类中,我保存了一个位置。

现在我有了一个 WorldObjects 列表。我想找到一个到给定点的最小距离的元素。

abstract class WorldObject 
{ 
    private Vector2D _position; 
 
    public Vector2D Position 
    { 
        get { return _position; } 
        set { _position = value; } 
    } 
 
    //... 
} 


private List<WorldObject> worldObjects; 
 
internal WorldObject GetNearestObject(Vector2D pos) 
{ 
    return worldObjects.Min(); 
} 

通常我可以通过在 WorldObject 中实现 IComparable 来搜索最小值。但是现在我需要这一点作为关系。我该怎么做?

请您参考如下方法:

您可以使用 .Aggregate为此:

return worldObjects 
    .Aggregate((result, current) => (current.Position.GetDistance(pos) 
                                     < result.Position.GetDistance(pos)) 
                                    ? current : result); 

.GetDistance 是计算 Vector2D 对象之间距离的假设函数。

另一种可能性是使用 morelinq 的 .MinBy :

return worldObjects.MinBy(wo => wo.Position.GetDistance(pos)); 

还有另一种可能性,但是它不必要地对对象进行排序:

return worldObjects.OrderBy(wo => wo.Position.GetDistance(pos)).First();