我需要根据纬度/经度值与用户当前纬度/经度的距离对列表进行排序。我还需要为每个条目显示以英里为单位的距离。
我发现this answer很近,但返回最近的经/纬度条目而不是列表。另外,我不了解以前能够转换为英里的距离单位。
简而言之,我需要一种方法...
class Location
{
double Lat { get; set; }
double Long { get; set; }
double Distance { get; set; }
}
public List<Location> SortLocations(Location current, List<Location> locations)
{
// ???
}
谢谢!
答案 0 :(得分:1)
您可以使用此处所述的GeoCoordinate
:Calculating the distance between 2 points in c#
一旦您可以计算出距离,就可以执行以下操作:
public List<Location> SortLocations(Location current, List<Location> locations)
{
foreach (var location in locations)
{
location.Distance = CalculateDistance(current, location);
}
// Return the list sorted by distance
return locations.OrderBy(loc => loc.Distance);
}
如果您不想在Distance
集合上设置locations
属性,则可以使用Select
:
return locationsWithDistance = locations.Select(
location => new Location
{
Lat = location.Lat,
Long = location.Long,
Distance = CalculateDistance(current, location)
}).OrderBy(location => location.Distance);