Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# รวม Dictionary ของสองคีย์

ใช้ HashSet<string> รวม Keys จากสอง Dictionary ด้วย UnionWith (Union Set)

ตัวอย่างโค้ด

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var dict1 = new Dictionary { {"one", 1}, {"Two", 2} };
        var dict2 = new Dictionary { {"Three", 3}, {"Four", 4} };
        
        var hSet = new HashSet(dict1.Keys);
        hSet.UnionWith(dict2.Keys);
        
        Console.WriteLine("Union of Dictionary Keys...");
        foreach (string val in hSet) Console.WriteLine(val);
    }
}

ผลลัพธ์

Union of Dictionary Keys...
one
Two
Three
Four

หมายเหตุ: รวมเฉพาะ Keys หากต้องการรวม Key-Value Pairs (รวม Value ด้วย) ต้องเขียน Logic เอง หรือใช้ LINQ Concat + ToDictionary (ระวัง Key ซ้ำ)