How to map from a list to a flat object in automapper .net

Viewed 33

I have a complex object that contains a list of products.


public class Container
{
    public List<Product> Products;
}

public class Product
{
    public string Name;
    public string Colour;
}
    
public class NewClass
{
    public string Name1;
    public string Colour1;
    public string Name2;
    public string Colour2;
    public string Name3;
    public string Colour3;
}

I want to map the container class to the new class.
I never will have more then 3 products but when I map it with automapper I get out of range exception because I don’t know if the list will contain 1,2 or 3 products.

cfg.CreateMap< Container, NewClass>()
    .ForMember(d => d.Name1, 
        opt => opt.MapFrom(src => src.Product[0].name)cfg.CreateMap< Container, NewClass().ForMember(d => d.Name2, 
       opt => opt.MapFrom(src => src.Product[1].name)cfg.CreateMap< Container, NewClass>()
    .ForMember(d => d.Name3, 
        opt => opt.MapFrom(src => src.Product[2].name)
    );

Any help obviously the code is an example but essentially I have to map from a list to a flat object

1 Answers

First of all, you don't need to call CreateMap multiple times for the same source/destination objects, you can simply chain ForMember calls.

Instead of accessing the specified index directly you can use the method ElementAtOrDefault which will return the element at the specified index or null if index is out of range.

So you can do this:

cfg.CreateMap<Container, NewClass>()
    .ForMember(dest => dest.Name1, opt => opt.MapFrom(src => src.Products.ElementAtOrDefault(0).Name))
    .ForMember(dest => dest.Name2, opt => opt.MapFrom(src => src.Products.ElementAtOrDefault(1).Name))
    .ForMember(dest => dest.Name3, opt => opt.MapFrom(src => src.Products.ElementAtOrDefault(2).Name));
Related