简体   繁体   中英

Automapper - Filtering data after mapping

I have the following code:

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

It works, but I want to remove duplicate values for SourceCarrierNames .

I try the following:

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())
    ;

but I see duplicate SourceCarrierNames inside every TransferRequestDto anyway.

Enumerable.Distinct Method

Returns: IEnumerable<TSource>

An IEnumerable that contains distinct elements from the source sequence.


Assign the result after distinct back to 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();
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM