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

LINQ分组拼接字段:按PolicyNumber分组并拼接ClientName

用C# LINQ实现按PolicyNumber分组并拼接ClientName

问题背景

现有如下定义的ReportsStatusEntity类:

public class ReportsStatusEntity
{
    public string PolicyNumber { get; set; }
    public string ClientName { get; set; }
    public bool HasIndividualBrokers { get; set; }
}

以及一个List<ReportsStatusEntity>类型的数据集:

{PolicyNumber = 1, ClientName = "John Doe", HasIndividualBrokers = True},
{PolicyNumber = 1, ClientName = "Sarah Doe", HasIndividualBrokers = True},
{PolicyNumber = 2, ClientName = "Paul Smith", HasIndividualBrokers = False},
{PolicyNumber = 3, ClientName = "Ryan Johnson", HasIndividualBrokers = False}

需求是按PolicyNumber分组,将同组的ClientName用&拼接,得到如下结果:

{PolicyNumber = 1, ReportStatusEntity = (PolicyNumber = 1, ClientName = "John Doe & Sarah Doe", HasIndividualBrokers = True)},
{PolicyNumber = 2, ReportStatusEntity = (PolicyNumber = 2, ClientName = "Paul Smith", HasIndividualBrokers = False)},
{PolicyNumber = 3, ReportStatusEntity = (PolicyNumber = 3, ClientName = "Ryan Johnson", HasIndividualBrokers = False)}

实现代码

可以通过LINQ的GroupBy分组后,结合String.Join拼接客户端名称,再构造目标结构:

// 假设reportList是你的List<ReportsStatusEntity>数据源
var groupedResult = reportList
    .GroupBy(entity => entity.PolicyNumber)
    .Select(group => new 
    {
        PolicyNumber = group.Key,
        ReportStatusEntity = new ReportsStatusEntity
        {
            PolicyNumber = group.Key,
            ClientName = string.Join(" & ", group.Select(e => e.ClientName)),
            // 同组内HasIndividualBrokers值一致,取第一个实体的属性值
            HasIndividualBrokers = group.First().HasIndividualBrokers
        }
    })
    .ToList();

代码说明

  • 分组:GroupBy(entity => entity.PolicyNumber)按保单编号对实体分组,每个分组的Key对应唯一的PolicyNumber。
  • 拼接名称:string.Join(" & ", group.Select(e => e.ClientName))提取分组内所有客户端名称,用&连接成单个字符串。
  • 处理布尔属性:假设同一保单编号下的HasIndividualBrokers值完全一致,直接取分组内第一个实体的属性值;如果业务中存在同组值不同的情况,需要根据需求调整(比如取逻辑与、逻辑或,或者抛出异常)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:55:39