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

หา Union ของ Dictionary ใน C# ด้วย HashSet.UnionWith()

Dictionary ไม่มี Union ตรงๆ แต่สามารถรวม Key ได้โดยใช้ HashSet<TKey> และ UnionWith()

ตัวอย่าง: รวม Key ของสอง Dictionary

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var dict1 = new Dictionary
        {
            ["water"] = 1,
            ["food"] = 2
        };

        var dict2 = new Dictionary
        {
            ["clothing"] = 3,
            ["shelter"] = 4
        };

        // สร้าง HashSet จาก Keys ของ dict1
        var keys = new HashSet(dict1.Keys);

        // รวม Keys จาก dict2
        keys.UnionWith(dict2.Keys);

        Console.WriteLine("Union of Dictionary Keys:");
        foreach (var key in keys)
            Console.WriteLine(key);
    }
}

ผลลัพธ์

Union of Dictionary Keys:
water
food
clothing
shelter

กรณี Key ซ้ำ (Collision Handling)

UnionWith() จะเก็บ Key เพียงค่าเดียว หากต้องการจัดการ Value ที่ชนกัน:

// Strategic Merge: รวม Value ตามกติกา
var merged = new Dictionary(dict1);

foreach (var kvp in dict2)
{
    if (merged.TryGetValue(kvp.Key, out var existing))
    {
        // กติกา: ใช้ค่าสูงสุด / ผลรวม / ค่าใหม่ล่าสุด
        merged[kvp.Key] = Math.Max(existing, kvp.Value);
    }
    else
    {
        merged[kvp.Key] = kvp.Value;
    }
}

Extension Method สำหรับ Dictionary Union

public static Dictionary Union(
    this Dictionary first,
    Dictionary second,
    Func mergeFunc = null)
{
    var result = new Dictionary(first);

    foreach (var kvp in second)
    {
        if (result.TryGetValue(kvp.Key, out var existing))
        {
            result[kvp.Key] = mergeFunc != null
                ? mergeFunc(existing, kvp.Value)
                : kvp.Value; // default: ใช้ค่าใหม่ทับ
        }
        else
        {
            result[kvp.Key] = kvp.Value;
        }
    }
    return result;
}

// ใช้งาน
var merged = dict1.Union(dict2, (v1, v2) => v1 + v2); // ผลรวม

กรณีใช้งานจริง

  • รวม Configuration จากหลายแหล่ง (Default + User + Environment)
  • Merge Cache จากหลาย Region
  • รวม Feature Flags จากหลาย Environment
  • Data Synchronization ระหว่าง Micro-services