映射后的自动映射器和过滤数据

Automapper and filtering data after mapping

我有以下代码:

        CreateMap<DevicesTransferRequest, TransferRequestDto>()
            .ForMember(d => d.SourceCarrierNames, o => o.MapFrom(s => s.DeviceMappings.Select(a => a.PreviousCarrier.Name).ToList()))

有效,但我想删除 SourceCarrierNames

的重复值

我尝试以下操作:

        CreateMap<DevicesTransferRequest, TransferRequestDto>()
            .ForMember(d => d.SourceCarrierNames, o => o.MapFrom(s => s.DeviceMappings.Select(a => a.PreviousCarrier.Name).ToList()))
            .AfterMap((src, dest) => dest.SourceCarrierNames.Distinct())
            ;

但我在每个 TransferRequestDto 中看到重复的 SourceCarrierNames

Enumerable.Distinct Method

Returns: IEnumerable<TSource>

包含来自源序列的不同元素的 IEnumerable。


将distinct后的结果赋值回dest.SourceCarrierNames

CreateMap<DevicesTransferRequest, TransferRequestDto>()
    .ForMember(d => d.SourceCarrierNames, o => o.MapFrom(s => s.DeviceMappings.Select(a => a.PreviousCarrier.Name).ToList()))
    .AfterMap((src, dest) => 
    {
        dest.SourceCarrierNames = dest.SourceCarrierNames
            .Distinct()
            .ToList();
    });