有了@LucianBargaoanu的pointer in the right direction和this answer的另一个问题,我得以提出一种使用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));
}
}
但是,这只能解决问题的第一部分。它无法解决我希望在属性名称上处理后缀的“增加的奖金”部分。为此,我提出了another question。
本文链接:https://www.f2er.com/3114225.html