2

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

Anders Abel
  • 67,989
  • 17
  • 150
  • 217
Positonic
  • 9,151
  • 14
  • 57
  • 84
  • 2
    In Sql Server 2008 there is a spatial index functionality which is built to help in these kind of scenarios, however I don't think it is supported by EF. – Anders Abel Aug 08 '11 at 17:17

2 Answers2

4

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.

BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
0

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.

Community
  • 1
  • 1
dizzwave
  • 4,013
  • 1
  • 19
  • 16