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

如何使用Mapster根据记录值排除指定数据条目?

问题

能否通过Mapster根据记录的值排除/忽略条目?

以下是具体场景:

实体类定义

public class Source
{
    public string Name { get; set; }
    public string Value { get; set; }
}

public class Destination
{
    public string Name { get; set; }
    public string Number { get; set; }
}

映射配置

TypeAdapterConfig<Source, Destination>.NewConfig()
    .Map(dest => dest.Name, src => src.Name)
    .Map(dest => dest.Number, src => src.Value);

数据源

var src = new List<Source>[]{
    new Source { Name = "one", Value = "1" },
    new Source { Name = "two", Value = "2" },
    new Source { Name = "three", Value = "3" }
};

需求:仅保留名称长度不超过3个字符的记录(即保留one和two,排除three),最终输出对应的Destination列表,排除Destination { Name = "three", Number = "3" }。


答案

无法通过Mapster实现该功能,这不属于Mapster的职责范畴,而是映射前后的业务逻辑。你可以在映射前先对数据源进行过滤,再执行映射操作,示例代码如下:

var filteredSrc = src.Where(s => s.Name.Length <= 3).ToList();
var result = filteredSrc.Adapt<List<Destination>>();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:00:22