[英]Covert from Object List to 2D Array property using Automapper
I am trying to convert an object list to a 2D Array property of another object using AutoMapper.我正在尝试使用 AutoMapper 将 object 列表转换为另一个 object 的二维数组属性。 This is an attempt to create GeoJson format like response.这是尝试创建类似响应的 GeoJson 格式。
Source Type来源类型
public class GeoCoordinateEntity
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
Target Type目标类型
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; }
}
I get get IEnumerable and trying to map it to the Coordinates property of GeoEvent.我得到了 IEnumerable 并尝试将它 map 到 GeoEvent 的 Coordinates 属性。 Here is where I am struggling.这就是我挣扎的地方。
CreateMap<IEnumerable<GeoCoordinateEntity>, GeoEvent>()
.ForMember(
dest => dest.GeometryType,
opt => opt.MapFrom(src => GeometryType.LineString))
.ForMember(
dest => dest.Coordinates,
opt => opt.MapFrom(src => /* Need Help */ ));
Can someone help me or point me in the right direction?有人可以帮助我或指出正确的方向吗?
Convert the source to IEnumerable<IEnumerable<double>>
and then write an extension method to convert it to 2D Array.将源转换为IEnumerable<IEnumerable<double>>
,然后编写扩展方法将其转换为 2D Array。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.