简体   繁体   English

使用自动映射器将字符串类型的列表映射到具有字符串属性的对象列表

[英]Mapping a list of type string to a list of objects with a string property using automapper

Here is my scenario. 这是我的情况。 I have a class, Class1, with a property of type string[] 我有一个类Class1,其属性类型为string []

Class Class1
{
    string[] strings{ get; set;}
}

and I want to map each string in the list to a string property within a list of type MyClass. 我想将列表中的每个字符串映射到MyClass类型的列表中的字符串属性。

Class MyClass
{
    string someString { get; set;]
}

So, using automapper it would be something like this 因此,使用automapper会像这样

Mapper.CreateMap<Class1, IEnumerable<MyClass>>().ForMember(dest => dest.someString, opts => opts.MapFrom(src => src.strings));

I know this won't work but I would imagine it would be something list this. 我知道这行不通,但我想这会列出一些东西。 I am not really sure where to go from here or if it is even possible any help would be greatly appreciated. 我不确定从这里走到哪里,或者是否有任何帮助将不胜感激。

There are a few ways you could accomplish this: 有几种方法可以实现此目的:

  1. Use ConstructUsing along with some LINQ: 与一些LINQ一起使用ConstructUsing

     Mapper.CreateMap<Class1, IEnumerable<MyClass>>() .ConstructUsing( src => src.strings.Select(str => new MyClass { someString = str })); 
  2. Use an "inner" mapping from string to MyClass and call that from ConstructUsing : 使用从stringMyClass的“内部”映射,然后从ConstructUsing调用

     Mapper.CreateMap<string, MyClass>() .ConstructUsing(str => new MyClass { someString = str }); Mapper.CreateMap<Class1, IEnumerable<MyClass>>() .ConstructUsing(src => Mapper.Map<IEnumerable<MyClass>>(src.strings)); 

Update based on comments : 根据评论更新

If you have multiple string[] properties in the source class and multiple corresponding string properties in the destination class, you could do something like this: 如果源类中有多个string[]属性,而目标类中有多个对应的string属性,则可以执行以下操作:

Mapper.CreateMap<Class1, IEnumerable<MyClass>>()
    .ConstructUsing(
        src => src.strings
            .Zip(src.strings2, (str1, str2) => new { str1, str2 })
            .Zip(src.strings3, (res1, str3) => 
                new MyClass 
                { 
                    someString = res1.str1,
                    someString2 = res1.str2, 
                    someString3 = str3
                }));

You'd basically call .Zip as many times as you have to. 基本上,您需要打.Zip次数很多。 This assumes all of the indexes match up for each array and the number of elements in each array is the same. 假设每个数组的所有索引都匹配并且每个数组中的元素数相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM