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

LINQ分组后正确赋值非分组列并聚合InnerList的问题

解决方案

你的问题出在直接取全局列表的第一个元素(list[0])来获取Property3和Name,这会导致所有分组都复用同一个值,而正确的做法是从当前分组内的元素中提取这些属性——从你的原始数据可以看出,同一分组(按Property1、Property2分组)内的所有元素,其Property3和Name是完全一致的。

修改后的LINQ查询如下:

var result = list
    .GroupBy(x => new { x.Property1, x.Property2 })
    .Select(g => new
    {
        g.Key.Property1,
        g.Key.Property2,
        // 从当前分组的任意元素中获取属性,同组内这些值完全一致
        Property3 = g.First().Property3,
        Name = g.First().Name,
        InnerList = g.SelectMany(x => x.InnerList)
            .GroupBy(x => x.Property4)
            .Select(g2 => new InnerList
            {
                Property4 = g2.Key,
                Percentage = g2.Sum(x => x.Percentage)
            })
    });

关键说明:

  • 分组后的g是当前分组的元素集合,由于同组内的Property3、Name属性值完全相同,直接取分组内第一个元素的对应属性即可得到该分组的正确值。
  • 内层的InnerList聚合逻辑无需改动,依然能按Property4对Percentage进行求和。

执行上述代码后,会输出你预期的结果:

{
List:[
{
Property1: "Apple",
Property2: "Fruit",
Property3: "USA",
Name: "aaa",
    InnerList:[{Property4 : 100,Percentage: 100.00},
               {Property4 : 50,Percentage: 50.00}]
},
{
Property1: "Mango",
Property2: "Fruit",
Property3: "INDIA",
Name: "bbb",
    InnerList:[{Property4 : 75,Percentage: 50.00}]
}
]}

内容的提问来源于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.11 10:50:46