简体   繁体   中英

Get list element with minimum distance in relation to a point

I have a class WorldObject . In this class I save a Position.

Now I have a List of WorldObjects . I want to find one element, that has the minimum distance to a given point.

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();
}

Normally I can search the minimum by implementing IComparable in WorldObject . But now I need this one point as relation. How can I do that?

You can use .Aggregate for this:

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

.GetDistance is assumed function for calculating distances between Vector2D objects.

Another possibility is to use morelinq's .MinBy :

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

Yet another possibility, however it sorts the objects unnecessarily:

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

assuming you have someway to get a distance between 2 positions:

internal WorldObject GetNearestObject(Vector2D pos)
{
    var minDistance = worldObjects.Min(wo => wo.Position.GetDistance(pos));
    return worldObjects.First(wo => wo.Position.GetDistance(pos) == minDistance);
}
internal WorldObject GetNearestObject(Vector2D pos)
{
    return worldObjects.OrderBy(wo => wo.Position.GetDistance(pos)).First();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM