2

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

As a follow up, how would you do this with multiple properties in the same class?
In the source or destination? If you update your question I'd be happy to take a look
The source, class1, contains n properties of type string[] and I want to map them into a list of MyClass that contains n properties of type string. I solved it with a custom resolver but I feel like this can be done without doing that.
@Chris: I updated my answer. If the number of properties is huge, you might want to look into a custom resolver instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.