AutoMapper可变长度列表的部分映射实现需求
实现列表的部分映射(保留目标列表原有元素)
针对你提出的需求——在源列表长度小于目标列表时,保留目标列表的所有原有元素,仅在源列表长度超出目标时才补充映射元素,可以通过以下两种方式实现:
方式1:手动控制映射逻辑
直接通过判断列表长度,决定是否执行映射操作,避免修改目标列表中已有的元素:
var mapper = config.CreateMapper(); List<ChildDTO> dest; if (listChild.Count > listChildDTO.Count) { // 仅映射源列表中超出目标长度的部分,添加到目标列表 var extraItems = mapper.Map<List<ChildDTO>>(listChild.Skip(listChildDTO.Count)); listChildDTO.AddRange(extraItems); dest = listChildDTO; } else { // 源列表长度不大于目标,直接保留原目标列表 dest = listChildDTO; }
方式2:自定义AutoMapper转换器
通过自定义列表类型的转换逻辑,让AutoMapper按照需求处理集合映射:
var config = new MapperConfiguration(cfg => { cfg.CreateMap<Child, ChildDTO>(); // 自定义集合转换规则:仅添加源中超出目标长度的元素,不修改已有元素 cfg.CreateMap<List<Child>, List<ChildDTO>>().ConvertUsing((source, destList, context) => { if (destList == null) { return context.Mapper.Map<List<ChildDTO>>(source); } var newElements = source.Skip(destList.Count).Select(item => context.Mapper.Map<ChildDTO>(item)); destList.AddRange(newElements); return destList; }); }); config.AssertConfigurationIsValid(); var mapper = config.CreateMapper(); var dest = mapper.Map<List<Child>, List<ChildDTO>>(listChild, listChildDTO);
最终结果
执行上述任意一种方案后,dest的元素将与你的期望完全一致:
2, "Mike", 33; 3, "Roy", 32;
内容的提问来源于stack exchange,提问作者Neeraj Singh Chouhan
相关产品推荐
相关产品推荐

