加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 是否可以在一种类型的集合上执行LINQ聚合到不同的结果类型

发布时间:2020-12-15 07:54:47 所属栏目:百科 来源:网络整理
导读:我想在一组(纬度,经度)对上使用单个LINQ聚合,并产生两个(纬度,经度)对: public Location { public double Latitude; public double Longitude;}ListLocation border = ...; 我可以通过以下方式轻松获得最小(纬度,经度)对: var minBorder = border.Aggregat
我想在一组(纬度,经度)对上使用单个LINQ聚合,并产生两个(纬度,经度)对:
public Location {
   public double Latitude;
   public double Longitude;
}

List<Location> border = ...;

我可以通过以下方式轻松获得最小(纬度,经度)对:

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
                                   }) ;

如果可能的话,我想使用单个聚合返回两个位置;最小(纬度,经度)对和最大(纬度,经度)对而不是一对.

如果我为结果声明一个类:

public class BorderBounds {

   public double MinLatitude;
   public double MinLongitude;

   public double MaxLatitude;
   public double MaxLongitude;
}

并修改聚合:

var borderBounds =  border.Aggregate( new Location()
                                 { Latitude = double.MaxValue,next) =>
                                   new BorderBounds()
                                   {
                                    ...
                                   }) ;

(current,next)参数假定为BorderBounds类型而不是Location.

有没有办法构建这样的聚合?将它转换为foreach是最好的吗?

解决方法

你能行的.我建议使边界可变,或者创建一个可变边界构建器,之后可以创建一个bounds对象,只是为了节省不必要的内存分配:
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;
        });

和班级

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; }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读