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

C#中对象列表去重并聚合内部列表数据的实现问题

问题:按多条件聚合对象列表中的内部列表数值

我有一个包含3条数据的对象列表,需要根据Property1、Property2以及InnerList中的Property3这三个条件判断对象是否匹配,匹配的话就累加对应Property3的Percentage数值。

原始数据

{
  "List": [
    {
      "Property1": "Apple",
      "Property2": "Fruit",
      "InnerList": [{"Property3": 100, "Percentage": 50.00}]
    },
    {
      "Property1": "Apple",
      "Property2": "Fruit",
      "InnerList": [{"Property3": 100, "Percentage": 50.00},
                   {"Property3": 50, "Percentage": 50.00}]
    },
    {
      "Property1": "Mango",
      "Property2": "Fruit",
      "InnerList": [{"Property3": 75, "Percentage": 50.00}]
    }
  ]
}

尝试过的代码

用Distinct()没效果,还写了一段LINQ查询,但不知道怎么给内部列表加条件,没得到期望结果:

var result = list
    .GroupBy(x=> new {x.Property1,x.Property2})
    .Select(grp => new Class
    {
        Property1 = grp.Key.Property1,
        Property2 = grp.Key.Property2,
        innerList = new List<InnerList>
        {
            new InnerList
            {
               Percentage = grp.SelectMany(x=> x.innerList).Sum(x=>x.Percentage)
            }
        }
    }).ToList();

期望结果

{
  "List": [
    {
      "Property1": "Apple",
      "Property2": "Fruit",
      "InnerList": [{"Property3": 100, "Percentage": 100.00},
                   {"Property3": 50, "Percentage": 50.00}]
    },
    {
      "Property1": "Mango",
      "Property2": "Fruit",
      "InnerList": [{"Property3": 75, "Percentage": 50.00}]
    }
  ]
}

解决方案

核心思路是先按外层的Property1和Property2分组,再在每个组内对InnerList按Property3分组累加Percentage,具体代码如下:

var result = list
    // 第一步:按外层的Property1和Property2分组,归拢同类型的外层对象
    .GroupBy(x => new { x.Property1, x.Property2 })
    .Select(grp => new Class
    {
        Property1 = grp.Key.Property1,
        Property2 = grp.Key.Property2,
        // 第二步:展开组内所有InnerList,按Property3分组后累加Percentage
        innerList = grp.SelectMany(x => x.innerList)
                       .GroupBy(inner => inner.Property3)
                       .Select(innerGrp => new InnerList
                       {
                           Property3 = innerGrp.Key,
                           Percentage = innerGrp.Sum(item => item.Percentage)
                       })
                       .ToList()
    })
    .ToList();

代码说明

  1. 外层GroupBy把相同Property1和Property2的对象归为一组,比如两个Apple-Fruit的对象会被分到同一组
  2. SelectMany把组内所有对象的InnerList展开成一个扁平列表,方便后续分组计算
  3. 内层GroupBy按Property3分组,对每个分组内的Percentage求和,得到该Property3对应的总占比
  4. 最后把聚合后的InnerList项收集起来,组装成符合要求的目标对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:01:37