简体   繁体   中英

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[]

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.

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

So, using automapper it would be something like this

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:

     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 :

     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:

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. This assumes all of the indexes match up for each array and the number of elements in each array is the same.

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.

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