简体   繁体   中英

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

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

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));

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