Skip to content
This repository has been archived by the owner on Nov 18, 2024. It is now read-only.

Commit

Permalink
Use LINQ to filter the locations that are within the bounding box.
Browse files Browse the repository at this point in the history
  • Loading branch information
jonsagara committed Feb 28, 2020
1 parent 3accd14 commit 6078a24
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions src/LocationByZip/SqlLocationRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ public async Task<IReadOnlyCollection<Location>> GetByCityStateAsync(string city
public async Task<IReadOnlyCollection<LocationInRadius>> GetLocationsInRadiusAsync(Location origin, RadiusBox bounds)
{
var locationsInBoundingBox = new List<LocationInRadius>();
var locationsInRadius = new List<LocationInRadius>();

using (var conn = new SqlConnection(_connectionString))
{
Expand All @@ -76,18 +75,17 @@ public async Task<IReadOnlyCollection<LocationInRadius>> GetLocationsInRadiusAsy
locationsInBoundingBox.AddRange(await conn.QueryAsync<LocationInRadius>(GetLocationsWithinRadiusSql(), args));
}

foreach (var locInBox in locationsInBoundingBox)
{
locInBox.DistanceToCenter = locInBox.DistanceFrom(origin);

if (locInBox.DistanceToCenter <= bounds.RadiusMiles)
return locationsInBoundingBox
// Compute the distance in miles from the origin (center of the circle).
.Select(l =>
{
locationsInRadius.Add(locInBox);
}
}

return locationsInRadius
.OrderBy(loc => loc.DistanceToCenter)
l.DistanceToCenter = l.DistanceFrom(origin);
return l;
})
// Only keep those locations that are actually within the radius.
.Where(l => l.DistanceToCenter <= bounds.RadiusMiles)
// Put the closest to the origin first.
.OrderBy(l => l.DistanceToCenter)
.ToArray();
}

Expand Down

0 comments on commit 6078a24

Please sign in to comment.