C# AutoMapper switch 運算式

使用 關鍵字比對運算式的 switch 模式

結論

CreateMap<TSource, TDest>()
    .ForMember(dest => dest.SomeDestProp, opt => opt.MapFrom((src, dest) =>
    {
        TSomeDestProp destinationValue;

        // mapping logic goes here

        return destinationValue;
    }));

補充

.ForMember(dst => dst.DisplayName,
    map => map.MapFrom((src, dst) =>
        src.Detail switch
        {
            var detail when detail.Option == "自訂" => detail.DisplayName,
            var detail when detail.Sex == "男" => detail.Name + "男士",
            var detail when detail.Sex == "女" => detail.Name + "女士",
            _ => default
        }
    ))

P.S. 其中 var detail 等於 src.Detail

參照

c# - Automapper: complex if else statement in ForMember - Stack Overflow

switch 運算式 - 使用 'switch' 運算式評估模式比對運算式 | Microsoft Learn

PS5