2

I have a Latitude Column in the db that has values that look like this 41.230524 , using HTML5 geolocation I get a more accurate Latitude that will look like this 41.230524081

I want to find the row in my db that is closest to the Latitude returned from Geolocation. I was thinking something like

var myCity = db.zipcodes.Where(x => LatFromGeoCode.StartsWith(x.Latitude)).FirstOrDefault();

the problem with that is there may be different cities in the db that start with 41.2XXXXX , I don't just want the first one , I want the closest match

I was thinking maybe a loop first trying to match the full LatFromGeo, then -1 char , then try again , it seems there must be a better way

4

1 回答 1

2

Find the one with the smallest mathematical difference:

double minDiff = db.zipcodes.Min(x => Math.Abs(x.Latitude - LatFromGeoCode));
var myCity = db.zipcodes.Where(x => Math.Abs(x.Latitude - LatFromGeoCode) == minDiff).FirstOrDefault();

(There is a way better way to do this with compression syntax, but I don't know linq to sql well enough to write it out quickly)

Here's the SQL if someone wants to convert it:

SELECT TOP 1 zipcode
FROM zipcodes z
WHERE ABS(z.Latitude - @LatFromGeoCode) = MIN(ABS(z.Latitude - @LatFromGeoCode))
于 2013-01-08T17:03:00.427 回答