c# - Automapper - 有条件地添加到列表

标签 c# automapper

情况是——

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/

相关文章:

c# - 使用 C# 代码在 HTML 中设置表格行的可见性?

c# - 如何使用 AutoMapper 根据展平属性的名称查找源属性

c# - 在 Visual Studio 加载项中 - 如何检索文本选择对象的属性 (Visual Commander)

c# - 如何在 OpenUrl 卡操作中回复消息?

c# - AutoMapper ProjectTo<>() 找不到 map

c# - AutoMapper C# 运行时映射取决于对象属性

c# - Automapper 数据库查找?

c# - AutoMapper 配置为所有 DateTime 属性使用本地时间

C# - 可移植类库 "XmlElement does not exist in the namespace System.XML"

c# - 访问 UserControl 资源中的元素