You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mapster映射时如何通过子对象布尔属性过滤列表中需映射的条目

你之前使用IgnoreIf不生效是因为IgnoreIf用于控制单个属性是否参与映射,而非过滤集合内的元素,无法实现子集合的按需筛选,以下是3种可行实现方案:

方案1:全局配置映射规则(推荐,复用性最高)

直接在Mapster的类型映射配置中,对源集合先做过滤再映射到目标集合,配置一次全局生效:

// 配置Parent -> ParentDto的映射规则
TypeAdapterConfig<Parent, ParentDto>.NewConfig()
    .Map(
        dest => dest.Children, 
        src => src.Children.Where(child => child.ShouldMap).ToList()
    );

// 映射调用,自动过滤ShouldMap=false的子元素
var parentDto = parent.Adapt<ParentDto>();

如果Child和ChildDto的属性名完全匹配,无需额外配置二者的映射规则,Mapster会自动完成元素转换。

方案2:单次映射临时配置

如果只需要在某一次映射时做过滤,不想影响全局规则,可以在调用Adapt时传入临时配置:

var parentDto = parent.Adapt<ParentDto>(config =>
    config.Map(
        dest => dest.Children, 
        src => src.Children.Where(child => child.ShouldMap).ToList()
    )
);

方案3:统一过滤带ShouldMap标识的实体

如果有多个实体都带有ShouldMap字段需要做映射过滤,可以做全局通用配置:

// 先定义公共接口
public interface IHasShouldMap
{
    bool ShouldMap { get; set; }
}

// 让Child实现该接口
class Child : IHasShouldMap
{
    public double SomeValue {get;set;}
    public bool ShouldMap {get;set;}
}

// 全局配置映射前自动过滤不符合条件的元素
TypeAdapterConfig.GlobalSettings.BeforeMapping = (src, dest, type) =>
{
    if (src is IEnumerable<IHasShouldMap> collection)
    {
        return collection.Where(item => item.ShouldMap);
    }
    return src;
};

这种方案适合多实体复用过滤规则的场景。


内容的提问来源于stack exchange,提问作者hablahat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:54:06