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

如何基于Category属性合并重复对象的Example属性值

合并重复分类的示例项

原始输入列表

[
    {
        "category": "animal",    
        "example": "cat"
    },
    {
        "category": "bird",
        "example": "parrot"
    },
    {
        "category": "animal",
        "example": "dog"
    }
]

目标输出列表

[
    {
        "category": "animal",    
        "example": ["cat", "dog"]
    },
    {
        "category": "bird",
        "example": "parrot"
    }
]

现有代码片段

var a = inputList.GroupBy(x => x.category);
var duplicates = a.Where(item => item.Count() > 1);

解决方案

无需单独提取重复项,直接基于分组结果生成目标格式的新列表即可,同时兼容单个示例和多个示例的场景:

var result = inputList
    .GroupBy(x => x.category)
    .Select(g => new 
    {
        category = g.Key,
        example = g.Count() > 1 ? (object)g.Select(x => x.example).ToList() : g.First().example
    })
    .ToList();

代码说明

  1. 按category字段分组,得到每个分类对应的所有条目集合
  2. 对每个分组做转换处理:
    • 若分组内条目数大于1,将所有条目的example值收集为列表,用(object)实现字符串与数组的类型兼容
    • 若分组内仅一条条目,直接取该条目的example值(保持原字符串类型)
  3. 最后将转换结果转为列表,得到符合要求的目标结构

注:不建议直接修改原inputList,因为原集合的单条目结构无法适配合并后的数组格式,生成新列表是更合理的处理方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:45:46