I am trying to convert an object list to a 2D Array property of another object using AutoMapper. This is an attempt to create GeoJson format like response.
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. 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.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.