C# - Automapper - 具有条件的Map元素

时间:2016-05-15 08:42:28

标签: c# arrays automapper

我有两个班级:

public class Customer
{
    public string FirstName { get; set;  }

    public string LastName { get; set; }

    public int Quantity { get; set; }
};

public class Customer_
{
    public string FirstNam { get; set; }

    public string LastNam { get; set; }

    public int Quantity { get; set; }
}

两者之间的映射与Automapper库:

Customer[] data =  new Customer[3];

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Customer, Customer_>()
   .ForMember(dest => dest.FirstNam, opt => opt.MapFrom(src => src.FirstName))
   .ForMember(dest => dest.LastNam, opt => opt.MapFrom(src => src.LastName));

});

IMapper mapper = config.CreateMapper();
Customer_[] desti = mapper.Map<Customer[], Customer_[]>(data);

它有效,但是如何仅映射满足条件的数组数据元素?例如:仅映射具有Quantity > x

的元素

感谢的

1 个答案:

答案 0 :(得分:1)

通常我会在映射到AutoMapper之前执行此操作:

Customer_[] desti = mapper.Map<Customer[], Customer_[]>(
    data.Where(c => c.Quantity > 10).ToArray());

不要试图将这种智能放入AutoMapper中,这会让人感到困惑并导致错误。