fedab
fedab

Reputation: 989

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?

Upvotes: 1

Views: 1796

Answers (3)

BartoszKP
BartoszKP

Reputation: 35891

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

Upvotes: 2

Tamir Vered
Tamir Vered

Reputation: 10287

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

Upvotes: 1

i3arnon
i3arnon

Reputation: 116548

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

Upvotes: 1

Related Questions