I have a class that contains a 2D-Array and a class with a collection of ArrayValue objects (shown below). How can i map between those 2 classes?
class ArrayMap {
int[,] map;
}
class CollectionMap {
ICollection<ArrayValue> map;
}
class ArrayValue {
int x;
int y;
int value;
}
Is it able to map these classes with Automapper or do I have to code my own mapping?
You can achieve this kind of custom mapping by implementing value converter :
public class CollectionMapConverter : IValueConverter<int[,], ICollection<ArrayValue>>
{
public ICollection<ArrayValue> Convert(int[,] sourceMember, ResolutionContext context)
{
var collection = new List<ArrayValue>();
for (var x = 0; x < sourceMember.GetLength(0); x++)
{
for (var y = 0; y < sourceMember.GetLength(1); y++)
{
collection.Add(new ArrayValue
{
value = sourceMember[x, y],
x = x,
y = y,
});
}
}
return collection;
}
}
then specify its usage when configurating map between ArrayMap
and CollectionMap
:
configuration.CreateMap<ArrayMap, CollectionMap>()
.ForMember(collectionMap => collectionMap.map, options =>
{
options.ConvertUsing(new CollectionMapConverter());
});
I assumed first dimension applies to a horizontal axis (X) and second one - to the vertical axis (Y). The current manner of reading the two-dimensional array is starting from the top left corner [0; 0] and going down (Y++), till the end of rows (Y), then stepping one column further (X++) and starting again the from the top (Y = 0). Repeat until the end of columns.
Eventually, mapping a two-dimensional int
array shown below:
+------------------->
| X
| +---+---+
| | 1 | 4 |
| +---+---+
| | 2 | 5 |
| +---+---+
| | 3 | 6 |
| +---+---+
|
|
v Y
will result in a collection of 6 ArrayValue
elements:
If you would like to have other order, then you would have construct the for
loops differently.
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.