情况是——
public class One
{
public string S1 { get;set; }
public string S2 { get;set; }
public string S3 { get;set; }
public string S4 { get;set; }
}
public class Two
{
public List<string> List1 { get;set; }
}
现在我想要的是用 One
的非 null 属性值填充 Two
中的列表。
是否有使用 AutoMapper
实现此目的的方法?
最佳答案
在这种情况下,您可以创建自己的自定义值解析器:
public class CustomResolver : ValueResolver<One, List<string>>
{
protected override List<string> ResolveCore(One source)
{
var result = new List<string>();
//your logic
if (!string.IsNullOrWhiteSpace(source.S1))
result.Add(source.S1);
if (!string.IsNullOrWhiteSpace(source.S2))
result.Add(source.S2);
if (!string.IsNullOrWhiteSpace(source.S3))
result.Add(source.S3);
if (!string.IsNullOrWhiteSpace(source.S4))
result.Add(source.S4);
return result;
}
}
映射配置:
Mapper.CreateMap<One, Two>()
.ForMember(dest => dest.List1, opt => opt.ResolveUsing<CustomResolver>());
通过这种方式,您可以为特定属性配置映射
关于c# - Automapper - 有条件地添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33996869/