C#存储和筛选包含一个双精度数组的列表

本文关键字:双精度 数组 列表 包含一 存储 筛选 | 更新日期: 2023-09-27 18:27:13

我有一系列十进制纬度/经度值格式的双精度。我想存储这些值,当要向列表中添加新值时,看看列表中是否已经有一个值,即纬度和经度的±0.0001。如果值在纬度或经度的±0.0001范围内,我不想存储它。

我想重新创建的是MongoDB Geospatial$near命令的一个版本。

有人能就如何处理这件事提供一些建议吗?有没有免费的c#地理空间库可以帮助我实现这个目标?

非常感谢你的建议。

C#存储和筛选包含一个双精度数组的列表

我不知道任何库,但您可以使用LINQ。这是一个List<Tuple<double, double>>:

var y = new Tuple<double, double>(15.25, 18.700001);
if(!coordinates.Any(x => Math.Abs(x.Item1 - y.Item1) <= 0.0001 || Math.Abs(x.Item2 - y.Item2) <= 0.0001)) {
    // No coordinate in the list is within ±0.0001 of either the latitude or the longitude
    coordinates.Add(y);
}

如果我理解正确,假设坐标被封装在某种容器中,这样的东西应该对你有用。

public class Coordinates
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}
public bool IsNear(List<Coordinates> coords, double lat, double lon, double tolerance)
{
    return coords.Any(p => Math.Abs(p.Latitude - lat) < tolerance || Math.Abs(p.Longitude - lon) < tolerance);
}

您需要计算两点之间的距离:

if (Math.Abs(Math.Sqrt((longitude - longitude_before) * (longitude - longitude_before) + (latitude - latitude_before) * (latitude - latitude_before))) > 0.0001)
{
   // Record new point
}

其中latitude_beater和longitude_beacher是记录路径中的最后一个条目——在我看来,不需要检查前面的点。如果事实证明是这样,并且性能成为一个问题,那么您将不得不查看范围搜索。