score:5
Here is Solution
var constValue = 57.2957795130823D
var constValue2 = 3958.75586574D;
var searchWithin = 20;
double latitude = ConversionHelper.SafeConvertToDoubleCultureInd(Latitude, 0),
longitude = ConversionHelper.SafeConvertToDoubleCultureInd(Longitude, 0);
var loc = (from l in DB.locations
let temp = Math.Sin(Convert.ToDouble(l.Latitude) / constValue) * Math.Sin(Convert.ToDouble(latitude) / constValue) +
Math.Cos(Convert.ToDouble(l.Latitude) / constValue) *
Math.Cos(Convert.ToDouble(latitude) / constValue) *
Math.Cos((Convert.ToDouble(longitude) / constValue) - (Convert.ToDouble(l.Longitude) / constValue))
let calMiles = (constValue2 * Math.Acos(temp > 1 ? 1 : (temp < -1 ? -1 : temp)))
where (l.Latitude > 0 && l.Longitude > 0)
orderby calMiles
select new location
{
Name = l.name
});
return loc .ToList();
score:1
var objAllListing = (from listing in _listingWithLanguageRepository.GetAll().Where(z => z.IsActive == true)
let distance = 12742 * SqlFunctions.Asin(SqlFunctions.SquareRoot(SqlFunctions.Sin(((SqlFunctions.Pi() / 180) * (listing.Listings.Latitude - sourceLatitude)) / 2) * SqlFunctions.Sin(((SqlFunctions.Pi() / 180) * (listing.Listings.Latitude - sourceLatitude)) / 2) +
SqlFunctions.Cos((SqlFunctions.Pi() / 180) * sourceLatitude) * SqlFunctions.Cos((SqlFunctions.Pi() / 180) * (listing.Listings.Latitude)) *
SqlFunctions.Sin(((SqlFunctions.Pi() / 180) * (listing.Listings.Longitude - sourceLongitude)) / 2) * SqlFunctions.Sin(((SqlFunctions.Pi() / 180) * (listing.Listings.Longitude - sourceLongitude)) / 2)))
where distance <= input.Distance
select new ListingFinalResult { ListingDetail = listing, Distance = distance }).ToList();//.Take(5).OrderBy(x => x.distance).ToList();
score:1
A netcore friendly solution. Refactor as needed.
public static System.Drawing.PointF getClosestPoint(System.Drawing.PointF[] points, System.Drawing.PointF query) {
return points.OrderBy(x => distance(query, x)).First();
}
public static double distance(System.Drawing.PointF pt1, System.Drawing.PointF pt2) {
return Math.Sqrt((pt2.Y - pt1.Y) * (pt2.Y - pt1.Y) + (pt2.X - pt1.X) * (pt2.X - pt1.X));
}
score:2
Do you have a valid range, outside of which the "hit" is not really relevant? If so, use
from l in locations where ((l.lat - point.lat) * (l.lat - point.lat)) + ((l.lng - point.lng) * (l.lng - point.lng)) < (range * range) select l
then find the hit with the smallest squared distance value within a loop of those results.
score:9
To elaborate on the comment by @Fung, if you are using Entity Framework / LINQ to Entities, if you try to use the GeoCoordinate.GetDistanceTo
method in a LINQ query, you'll get a runtime NotSupportedException with the message:
LINQ to Entities does not recognize the method 'Double GetDistanceTo(System.Device.Location.GeoCoordinate)' method, and this method cannot be translated into a store expression.
With Entity Framework version 5 or 6, an alternative is to use the System.Data.Spatial.DbGeography class. For example:
DbGeography searchLocation = DbGeography.FromText(String.Format("POINT({0} {1})", longitude, latitude));
var nearbyLocations =
(from location in _context.Locations
where // (Additional filtering criteria here...)
select new
{
LocationID = location.ID,
Address1 = location.Address1,
City = location.City,
State = location.State,
Zip = location.Zip,
Latitude = location.Latitude,
Longitude = location.Longitude,
Distance = searchLocation.Distance(
DbGeography.FromText("POINT(" + location.Longitude + " " + location.Latitude + ")"))
})
.OrderBy(location => location.Distance)
.ToList();
_context
in this example is your previously-instantiated DbContext instance.
Although it's currently undocumented in MSDN, the units returned by the DbGeography.Distance method appear to be meters. See: System.Data.Spatial DbGeography.Distance units?
score:60
You could first convert the location data in database to System.Device.Location.GeoCoordinate
, then use LINQ to find the nearest one.
var coord = new GeoCoordinate(latitude, longitude);
var nearest = locations.Select(x => new GeoCoordinate(x.Latitude, x.Longitude))
.OrderBy(x => x.GetDistanceTo(coord))
.First();
Source: stackoverflow.com
Related Query
- Find closest location with longitude and latitude
- Using linq to find out the nearest data with the given latitude and longitude
- How to find point closest to 0,0 point with LINQ and C#
- Find all nearby customers within a given distance using longitude and latitude
- Find address by latitude and longitude from a point (lat, lng) given
- How do I find 10 elements by longitude and latitude in 1 km radius using LINQ?
- Find closest and smaller value in a list in C# with linq?
- What does this C# code with an "arrow" mean and how is it called?
- Find an XElement with a certain attribute name and value with LINQ
- Algorithm to calculate nearest location based on longitude & latitude
- C# - LINQ - shortest distance by GPS latitude and longitude
- Avoid extra loop and could not find implementation of query pattern for source type int Select not found
- C# - Linq optimize code with List and Where clause
- Find closest value in an array List with linq?
- Stubbing Code for Test With Linq Expressions and Lambdas
- c# find item in list returned by LINQ query and compare its value with another item in list
- Find pattern in json with json.net and linq
- Problem with Convert.ToInt32 and getting error Index and length must refer to a location within the string
- LINQ/Lambda expression: Join lists and find the average counts of data with the given formula
- Find average and max time after grouping with linq
- How to find keys in a Dict<int,List<Tuple<string,string>>> such that the list contains elements with given Item1 and Items
- C# How to loop through an array and find array with most recent date?
- Iterate through a list of objects and find the one with the highest price and set it to Active and disable all others
- Optimized code for Insert and Update in one method with LINQ?
- Find all subsets with Enumerable.Zip or bitwise AND logic
- How to bind and save an object containing a list of objects to database context in ASP.NET MVC with EF code first?
- Calling a shared code from Page method and WebApi Controller with Razor Pages
- find item in list , and get other item from other list at same location using linq
- Find items with same property from list and pick the cheaper of the two items
- How to iterate in a list to find names and values with linq
More Query from same tag
- How to put where condition in select condition in Linq query
- How can avoid repeat same where in Entity Framework
- C# Linq GroupBy and Count field
- C#, Two lists of object find differences between one variable in both objects
- Cached entities making round trip to database
- Exclude elements that appear in another sequence
- Select a single object from Entity IQueryable List of object
- Better way to remove characters that aren't ASCII 32 to 175 C#
- How to return Anonymous Type while using Linq
- Filter a nested collections with LINQ "Include"
- dynamically add nodes in xml using linq
- How To Know If A Certain Form Is Open?
- Is there a "split list" method in c#?
- Extension Method to assign value to a field in every item?
- Converting windows forms application from .NET 3.5 to .NET 4
- Filter nodes out of a XmlNodeList (Sytem.Xml. XmlNodeList)
- Custom object using Except failing to use IEqualityComparer<T>
- Why is this query resolving to a DataQuery
- Linq: DataTable to List. Cast issue
- Combine strings to List in Queryable
- What is the equivalent T-SQL select query for the attached linq query?
- multiple resultsets vs multiple calls for performance
- Linq IEnumerable<IGrouping<string, Class>> back to List<Class>
- LINQ query... How to perform?
- Is it possible to use Linq to group by changes in a series rather than simply by matching on a group item?
- In a DataTable object, how can I get a list of columns and their min/max string.Length?
- Linq: how i get the value of an object
- Why are my LINQ OrderBys not working?
- LINQ - Left Join And Group By
- Entity equality across different Linq-to-SQL contexts