如何使用自动映射器将 2D 数组映射到 "array-objects" 的集合?
How to map a 2D-Array to a collection of "array-objects" with automapper?
我有一个包含二维数组的 class 和一个包含 ArrayValue 对象集合的 class(如下所示)。我如何在这 2 个 class 之间映射?
class ArrayMap {
int[,] map;
}
class CollectionMap {
ICollection<ArrayValue> map;
}
class ArrayValue {
int x;
int y;
int value;
}
它能用 Automapper 映射这些 classes 还是我必须编写自己的映射代码?
您可以通过实施 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;
}
}
然后在ArrayMap
和CollectionMap
之间配置映射时指定其用法:
configuration.CreateMap<ArrayMap, CollectionMap>()
.ForMember(collectionMap => collectionMap.map, options =>
{
options.ConvertUsing(new CollectionMapConverter());
});
我假定第一个维度适用于水平轴 (X),第二个维度适用于垂直轴 (Y)。目前读取二维数组的方式是从左上角开始[0; 0] 并向下 (Y++),直到行的末尾 (Y),然后进一步步进一列 (X++) 并再次从顶部开始 (Y = 0)。重复直到列的末尾。
最终映射出一个二维int
数组,如下所示:
+------------------->
| X
| +---+---+
| | 1 | 4 |
| +---+---+
| | 2 | 5 |
| +---+---+
| | 3 | 6 |
| +---+---+
|
|
v Y
将产生 6 个 ArrayValue
元素的集合:
如果您想要其他顺序,那么您将以不同的方式构建 for
循环。
我有一个包含二维数组的 class 和一个包含 ArrayValue 对象集合的 class(如下所示)。我如何在这 2 个 class 之间映射?
class ArrayMap {
int[,] map;
}
class CollectionMap {
ICollection<ArrayValue> map;
}
class ArrayValue {
int x;
int y;
int value;
}
它能用 Automapper 映射这些 classes 还是我必须编写自己的映射代码?
您可以通过实施 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;
}
}
然后在ArrayMap
和CollectionMap
之间配置映射时指定其用法:
configuration.CreateMap<ArrayMap, CollectionMap>()
.ForMember(collectionMap => collectionMap.map, options =>
{
options.ConvertUsing(new CollectionMapConverter());
});
我假定第一个维度适用于水平轴 (X),第二个维度适用于垂直轴 (Y)。目前读取二维数组的方式是从左上角开始[0; 0] 并向下 (Y++),直到行的末尾 (Y),然后进一步步进一列 (X++) 并再次从顶部开始 (Y = 0)。重复直到列的末尾。
最终映射出一个二维int
数组,如下所示:
+------------------->
| X
| +---+---+
| | 1 | 4 |
| +---+---+
| | 2 | 5 |
| +---+---+
| | 3 | 6 |
| +---+---+
|
|
v Y
将产生 6 个 ArrayValue
元素的集合:
如果您想要其他顺序,那么您将以不同的方式构建 for
循环。