Positonic
Positonic

Reputation: 9411

Doing Mathematical calulations in Order by with Linq

I am quite new to Linq to Entity and having some trouble.

Here's my Search repository:

 public static List<Centre> Search(Search search)
 {
    using (var context = new MeetingRoomsContext())
    {
        var query = context.Centres
                .Include("Geo")
                .OrderBy( NEED HELP WITH THIS PART )

        return query.ToList();
    }
 }

I am getting a search object which contains co-ordinates like this:

Search.LongLat = "(-6.265275, 53.334442)"

I need to break that out and do some maths against the co-ordinates in the DB in order to order results by the closest to the searched point for first.

In mathematical terms it would be pythagoras:

squareRootOf((difference in latitude * difference in latitude) + 
             (difference in longitude * difference in longitude))

Really haven't a clue how to do this. Any help appreciated greatly

Upvotes: 2

Views: 211

Answers (2)

There is no need for a square root at all; ordering by the square of the distance is the same as ordering by the distance:

.OrderBy(x => (x.Latitude - target.Latitude)*(x.Latitude - target.Latitude)
              + (x.Longitude - target.Longitude)*(x.Longitude - target.Longitude))

This trick is often used in collision detection (such as for video games) to avoid having to calculate many square roots.

Upvotes: 4

dizzwave
dizzwave

Reputation: 4479

How about implementing your own IComparer that calculates that pythagorean square root? Then the OrderBy will automatically compare off that.
See this post for an example.

Upvotes: 0

Related Questions