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

C#中合并两个字典并将相同键对应值组合为列表的实现问题

C# 字典按规则合并实现方案

核心实现逻辑

  • 提取两个字典所有键的并集作为新字典的键集合
  • 遍历每个键,分别从两个原字典中取值,不存在对应键时用空字符串填充
  • 将每组两个值组装为列表作为新字典对应键的值

完整代码示例

using System;
using System.Collections.Generic;
using System.Linq;

class DictMergeDemo
{
    static void Main()
    {
        // 示例输入字典
        Dictionary<int, string> D1 = new Dictionary<int, string>()
        {
            {2, "a"},
            {3, "b"},
            {4, "c"}
        };
        Dictionary<int, string> D2 = new Dictionary<int, string>()
        {
            {1, "e"},
            {2, "f"},
            {4, "h"},
            {5, "i"}
        };

        // 合并逻辑
        var allKeys = D1.Keys.Union(D2.Keys).OrderBy(k => k);
        Dictionary<int, List<string>> D3 = new Dictionary<int, List<string>>();
        foreach (int key in allKeys)
        {
            string val1 = D1.TryGetValue(key, out string v1) ? v1 : string.Empty;
            string val2 = D2.TryGetValue(key, out string v2) ? v2 : string.Empty;
            D3.Add(key, new List<string> { val1, val2 });
        }

        // 输出验证
        foreach (var item in D3)
        {
            Console.WriteLine($"{item.Key}: [\"{item.Value[0]}\", \"{item.Value[1]}\"]");
        }
    }
}

LINQ简化写法

如果偏好链式调用,可以直接用LINQ生成结果:

var D3 = D1.Keys.Union(D2.Keys)
    .OrderBy(k => k)
    .ToDictionary(
        key => key,
        key => new List<string>
        {
            D1.TryGetValue(key, out var v1) ? v1 : "",
            D2.TryGetValue(key, out var v2) ? v2 : ""
        });

注意事项

  • 代码中OrderBy(k => k)是为了和示例输出的键排序一致,不需要排序可直接删除该段
  • 如果字典的键值类型不是int和string,调整对应泛型参数即可,合并逻辑通用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:33:01