[英]Transpose member arrays into collection of objects with corresponding singular members using AutoMapper
我有以下課程:
class Foo
{
public int X[];
public int Y[];
public int Z[];
}
class Bar
{
public int X;
public int Y;
public int Z;
}
我希望創建以下 AutoMapper map:
CreateMap<Foo, IEnumerable<Bar>>
這是 map 單個Foo
object 到Bar
的集合,這樣Foo.X[i]
和Foo.Y[i]
Bar[i].Y
map 到 Bar.i Bar[i].X
。 arrays 將始終具有相同的長度。 使用內置功能的 AutoMapper 是否可以做到這一點? 理想情況下,我想避免必須以編程方式明確 map 每個成員。
作為額外的獎勵,我還想使用RecognizePostfixes("Postfix")
和以下版本的Foo
支持源上的后綴:
class Foo
{
public int XPostfix[];
public int YPostfix[];
public int ZPostfix[];
}
通過@LucianBargaoanu 指向正確方向的指針以及另一個問題的答案,我能夠使用ITypeConverter
和IEnumerable
擴展方法提出解決方案。
這是ITypeConverter
:
class TransposeConverter<TSource, TDestination> : ITypeConverter<TSource, IEnumerable<TDestination>> where TDestination : class, new()
{
public IEnumerable<TDestination> Convert(TSource source, IEnumerable<TDestination> destination, ResolutionContext context)
{
// Zip all the member collections from the source object together into a single collection then map to the destination based on the property names.
return typeof(TSource).GetProperties()
.Select(p => ((IEnumerable)p.GetValue(source)).Cast<object>().Select(item => (item, p.Name)))
.Zip(s => context.Mapper.Map<TDestination>(s.ToDictionary(k => k.Name, e => e.item)));
}
}
這是Zip
擴展方法:
public static IEnumerable<TResult> Zip<T, TResult>(this IEnumerable<IEnumerable<T>> collections, Func<IEnumerable<T>, TResult> resultSelector)
{
var enumerators = collections.Select(s => s.GetEnumerator()).ToArray();
while (enumerators.All(e => e.MoveNext()))
{
yield return resultSelector(enumerators.Select(e => e.Current));
}
}
但是,這只解決了問題的第一部分。 它不能解決我希望處理屬性名稱后綴的“額外獎勵”部分。 我為此提出了另一個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.