我想在一组(纬度,经度)对上使用单个LINQ聚合,并产生两个(纬度,经度)对:
public Location {
public double Latitude;
public double Longitude;
}
List<Location> border = ...;
Run Code Online (Sandbox Code Playgroud)
我可以通过以下方式轻松获得最小(纬度,经度)对:
var minBorder = border.Aggregate( new Location()
{ Latitude = double.MaxValue, Longitude = double.MaxValue },
(current, next) =>
new Location()
{
Latitude = (next.Latitude < current.Latitude) ? next.Latitude : current.Latitude,
Longitude = (next.Longitude < current.Longitude) ? next.Longitude : current.Longitude
}) ;
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我想使用单个聚合返回两个位置; 最小(纬度,经度)对和最大(纬度,经度)对而不是一对.
如果我为结果声明一个类:
public class BorderBounds {
public double MinLatitude;
public double MinLongitude;
public double MaxLatitude;
public double MaxLongitude;
}
Run Code Online (Sandbox Code Playgroud)
并修改聚合:
var borderBounds = border.Aggregate( new Location()
{ Latitude = double.MaxValue, Longitude = double.MaxValue },
(current, next) =>
new BorderBounds()
{
...
}) ;
Run Code Online (Sandbox Code Playgroud)
的(current, next)参数被假定为类型的BorderBounds,而不是Location.
有没有办法构建这样的聚合?简单地将其转换为foreach?是否最好?
你能行的。我建议使边界可变,或者创建一个可变边界构建器,可以在之后创建一个边界对象,只是为了节省不必要的内存分配:
locations.Aggregate(new Bounds(), (bounds, location) =>
{
if (bounds.MinLat > location.Latitude) bounds.MinLat = location.Latitude;
if (bounds.MaxLat < location.Latitude) bounds.MaxLat = location.Latitude;
if (bounds.MinLon > location.Longitude) bounds.MinLon = location.Longitude;
if (bounds.MaxLon < location.Longitude) bounds.MaxLon = location.Longitude;
return bounds;
});
Run Code Online (Sandbox Code Playgroud)
还有课程
internal class Location
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
internal class Bounds
{
public Bounds()
{
MinLat = double.MaxValue;
MaxLat = double.MinValue;
MinLon = double.MaxValue;
MaxLon = double.MinValue;
}
public double MinLat { get; set; }
public double MaxLat { get; set; }
public double MinLon { get; set; }
public double MaxLon { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
169 次 |
| 最近记录: |