【问题标题】:Covert from Object List to 2D Array property using Automapper使用 Automapper 从对象列表转换为二维数组属性
【发布时间】:2021-08-18 21:28:33
【问题描述】:

我正在尝试使用 AutoMapper 将对象列表转换为另一个对象的二维数组属性。这是一种尝试创建 GeoJson 格式的响应。

来源类型

public class GeoCoordinateEntity
{
   public double Latitude { get; set; }
   public double Longitude  { get; set; }
}

目标类型

public class GeoEvent
{
   // Enum which in this case will be always Maps to LineString.
   public GeometryType GeometryType { get; set; }
   // Trying to Map this format??....
   public double[,] Coordinates { get; set; }
}

我得到 IEnumerable 并尝试将其映射到 GeoEvent 的 Coordinates 属性。这是我苦苦挣扎的地方。

 CreateMap<IEnumerable<GeoCoordinateEntity>, GeoEvent>()
    .ForMember(
        dest => dest.GeometryType,
        opt => opt.MapFrom(src => GeometryType.LineString))
    .ForMember(
        dest => dest.Coordinates,
        opt => opt.MapFrom(src => /* Need Help */ ));

有人可以帮助我或指出正确的方向吗?

【问题讨论】:

  • 如果没有 AM,你会如何使用 LINQ?

标签: c# automapper geojson


【解决方案1】:

将源转换为IEnumerable&lt;IEnumerable&lt;double&gt;&gt;,然后编写扩展方法将其转换为二维数组。

 CreateMap<IEnumerable<GeoCoordinateEntity>, GeoEvent>()
        .ForMember(dest => dest.Coordinates, opt => opt.MapFrom(source => 
        source.Select(prop => new List<double>
        {
            prop.Latitude,
            prop.Longitude
        })
        .To2DArray()));

Extension Method to Create Two Dimensional Array

static class EnumerableExtensions
{
    public static T[,] To2DArray<T>(this IEnumerable<IEnumerable<T>> source)
    {
        var data = source
            .Select(x => x.ToArray())
            .ToArray();

        var res = new T[data.Length, data.Max(x => x.Length)];
        for (var i = 0; i < data.Length; ++i)
        {
            for (var j = 0; j < data[i].Length; ++j)
            {
                res[i, j] = data[i][j];
            }
        }

        return res;
    }
}

【讨论】:

    猜你喜欢
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 2020-11-10
    • 2015-10-22
    • 1970-01-01
    • 2011-04-14
    相关资源
    最近更新 更多