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

使用LINQ对自定义对象列表的属性值进行求和

如何合并多个Product列表并按Key1+Key2分组求和Count属性?

这个需求用C#的LINQ就能轻松实现,核心思路是先合并所有列表,再按Key1和Key2的组合分组,最后对每个分组的Count属性分别求和。下面是完整的实现方案:

完整代码示例

首先我们先模拟你给出的示例数据,然后执行合并逻辑:

// 定义Product类(和你给出的一致)
public class Product
{
    public string Key1 { get; set; }
    public string Key2 { get; set; }
    public int Count1 { get; set; }
    public int Count2 { get; set; }
}

class Program
{
    static void Main()
    {
        // 示例列表1
        var list1 = new List<Product>
        {
            new Product { Key1 = "Key1", Key2 = "Key2", Count1 = 1, Count2 = 2 },
            new Product { Key1 = "Key2", Key2 = "Key3", Count1 = 3, Count2 = 4 }
        };

        // 示例列表2
        var list2 = new List<Product>
        {
            new Product { Key1 = "Key1", Key2 = "Key2", Count1 = 5, Count2 = 6 },
            new Product { Key1 = "Key2", Key2 = "Key3", Count1 = 7, Count2 = 8 }
        };

        // 步骤1:合并所有Product列表
        var allProducts = list1.Concat(list2);

        // 步骤2:分组并求和Count属性
        var mergedProducts = allProducts
            .GroupBy(product => new { product.Key1, product.Key2 })
            .Select(group => new Product
            {
                Key1 = group.Key.Key1,
                Key2 = group.Key.Key2,
                Count1 = group.Sum(p => p.Count1),
                Count2 = group.Sum(p => p.Count2)
            })
            .ToList();

        // 验证输出结果
        foreach (var p in mergedProducts)
        {
            Console.WriteLine($"{p.Key1}, {p.Key2}, {p.Count1}, {p.Count2}");
        }
    }
}

代码逻辑说明

  1. 合并列表:使用Concat方法将多个列表合并为一个IEnumerable<Product>,如果有更多列表,只需继续追加Concat(list3).Concat(list4)即可;如果列表数量不确定,也可以用SelectMany展开一个列表的列表:

    var allLists = new List<List<Product>> { list1, list2, list3 };
    var allProducts = allLists.SelectMany(l => l);
    
  2. 分组逻辑:GroupBy使用匿名类型作为分组键,因为匿名类型会自动基于属性值生成Equals和GetHashCode方法,能正确识别Key1和Key2都相同的项为同一组。

  3. 求和与投影:对每个分组,用Sum计算Count1和Count2的总和,然后创建新的Product对象,将分组键的Key1、Key2和求和后的Count值赋值进去,最后转为List<Product>得到最终结果。

运行这段代码后,输出结果完全符合你的期望:

Key1, Key2, 6, 8
Key2, Key3, 10, 12

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:24:56