Search code examples
c#sql-serverlinqsqlgeography

Using linq to find out the nearest data with the given latitude and longitude


I have a data table which stores has data stored as per latitude and longitude.
enter image description here

I need to use LINQ query to filter in this datable and find the nearest location from the given latitude and longitude.

For example: 28.9873 -- Latitude, 80.1652 -- Longitude


Solution

  • Try this:

    var minDistance = collection.Min( x => Math.Sqrt( Math.Pow( wantedLatitude - x.Latitude ) + Math.Pow( wantedLongitude - x.Longitude )));
    
    var closestLocation = collection.First( x => Math.Sqrt( Math.Pow( wantedLatitude - x.Latitude ) + Math.Pow(wantedLongitude - x.Longitude )) == minDistance );
    

    It goes through collection twice, so I suggest to optimize it by finding Min element in first run, you can easily find how to do it in other questions on SO, and to and encapsulate calculation of distance to own method, but you get the idea.