Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chương trình C# gộp hai Dictionary

Gộp Key của hai Dictionary dùng HashSet + UnionWith.

Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("laptop", 1); dict1.Add("desktop", 2);

Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("desktop", 3); dict2.Add("tablet", 4); dict2.Add("mobile", 5);

HashSet<string> hSet = new HashSet<string>(dict1.Keys);
hSet.UnionWith(dict2.Keys);

Ví dụ

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var dict1 = new Dictionary<string, int>();
        dict1.Add("laptop", 1); dict1.Add("desktop", 2);
        
        var dict2 = new Dictionary<string, int>();
        dict2.Add("desktop", 3); dict2.Add("tablet", 4); dict2.Add("mobile", 5);
        
        var hSet = new HashSet<string>(dict1.Keys);
        hSet.UnionWith(dict2.Keys);
        
        Console.WriteLine("Dictionary đã gộp (Keys):");
        foreach (string val in hSet) Console.WriteLine(val);
    }
}

Kết quả: laptop, desktop, tablet, mobile (desktop chỉ 1 lần)

Gộp cả Key-Value (merge value):

var merged = new Dictionary<string, int>(dict1);
foreach (var kvp in dict2)
    merged[kvp.Key] = kvp.Value; // dict2 value ghi đè dict1

// Hoặc LINQ (C# 11+)
var merged = dict1.Concat(dict2)
    .GroupBy(k => k.Key)
    .ToDictionary(g => g.Key, g => g.Last().Value);