Libor Zapletal Libor Zapletal - 14 days ago 11
C# Question

C# - LINQ - shortest distance by GPS latitude and longitude

I have database and in it I have class hotel with gps coordinates. I want to get closest places to coordinates which I choose.

I think It should look like this (I found many example codes here and like this one):

var coord = new GeoCoordinate(latitude, longitude);
var nearest = (from h in db.hotels
let geo = new GeoCoordinate(h.gps.lat, h.gps.lng)
orderby geo.GetDistanceTo(coord)
select h).Take(10);


The problem is that I have this error when I tried to search for something:


Only parameterless constructors and initializers are supported in LINQ
to Entities


I tried to google it and I found that dividing that linq into two can help me but I am not sure how. Thanks for help.

Answer

You can use the object initializer instead of parameterized constructor:

var nearest = (from h in db.hotels
           let geo = new GeoCoordinate{ Latitude = h.gps.lat, Longitude = h.gps.lng}
           orderby geo.GetDistanceTo(coord)
           select h).Take(10);

But you will likely have problems caused by the GetDistanceTo method, could you provide the implementation of that method?