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

C#如何使用Linq对Dictionary字典列表实现分组聚合操作

实现方案

基础实现代码

using System.Linq;

// 你的原有itemList定义保持不变
List<Dictionary<string, object>> result = itemList
    // 按Item和Category组合为分组键
    .GroupBy(d => new 
    {
        Item = d["Item"].ToString(),
        Category = d["Category"].ToString()
    })
    // 每个分组生成新的字典,累加Quantity
    .Select(g => new Dictionary<string, object>
    {
        { "Item", g.Key.Item },
        { "Category", g.Key.Category },
        { "Quantity", g.Sum(d => Convert.ToInt32(d["Quantity"])) }
    })
    .ToList();

逻辑说明

  • 分组阶段使用匿名类型作为分组键,C#匿名类型默认按属性值判断相等,可保证相同Item和Category的条目被分到同一组
  • 累加阶段需要先把object类型的Quantity转换为整数类型再做求和运算
  • 最终每个分组直接实例化符合要求格式的字典,转成List后就是目标结果

健壮性增强版本(可选)

如果需要兼容字段缺失、数值格式异常等边界场景,可以使用带校验的实现:

List<Dictionary<string, object>> result = itemList
    // 过滤掉缺字段、Quantity不可转换的无效条目
    .Where(d => d.ContainsKey("Item") 
                && d.ContainsKey("Category") 
                && d.ContainsKey("Quantity") 
                && d["Quantity"] is IConvertible)
    .GroupBy(d => new 
    {
        Item = d["Item"]?.ToString() ?? string.Empty,
        Category = d["Category"]?.ToString() ?? string.Empty
    })
    .Select(g => new Dictionary<string, object>
    {
        { "Item", g.Key.Item },
        { "Category", g.Key.Category },
        { "Quantity", g.Sum(d => int.TryParse(d["Quantity"].ToString(), out int qty) ? qty : 0) }
    })
    .ToList();

效果验证

你可以通过以下代码打印结果验证:

foreach (var item in result)
{
    Console.WriteLine($"Item: {item["Item"]}, Category: {item["Category"]}, Quantity: {item["Quantity"]}");
}

运行输出和你要求的结果完全一致:

Item: 001, Category: A, Quantity: 11
Item: 002, Category: B, Quantity: 8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 17:15:03