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

เมธอด UnionWith ใน C# - การรวมชุดข้อมูลแบบไม่ซ้ำ (HashSet)

HashSet<T>.UnionWith() ใช้รวมข้อมูลจากสองคอลเลกชันให้ได้ค่าที่ไม่ซ้ำกัน (Union) โดยแก้ไข HashSet ต้นทางโดยตรง (In-place)

ลายเซ็นเมธอด

public void UnionWith(IEnumerable<T> other);

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

using System;
using System.Collections.Generic;

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

        var dict2 = new Dictionary
        {
            ["pen"] = 3,      // Key ซ้ำ
            ["eraser"] = 4
        };

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

        // รวม Keys จาก dict2 (pen จะไม่ซ้ำ)
        keys.UnionWith(dict2.Keys);

        Console.WriteLine("Merged Keys:");
        foreach (var key in keys)
            Console.WriteLine(key);
    }
}

ผลลัพธ์

Merged Keys:
pencil
pen
eraser

คุณสมบัติสำคัญ

  • In-place: แก้ไข HashSet เดิม ไม่สร้างออบเจกต์ใหม่
  • O(n): ประสิทธิภาพดี ใช้ Hash-based Lookup
  • Idempotent: เรียกซ้ำหลายครั้งผลเหมือนเดิม
  • Thread-unsafe: ต้องใช้ Lock เองใน Multi-threaded Environment

เปรียบเทียบกับ LINQ Union()

คุณสมบัติHashSet.UnionWith()Enumerable.Union()
คืนค่าvoid (แก้ไขตัวเดิม)IEnumerable<T> (สร้างใหม่)
ประสิทธิภาพO(n) - Hash-basedO(n) - Hash-based (Deferred)
ลำดับข้อมูลไม่รับประกันรักษาลำดับของแหล่งที่มา
ใช้กับHashSet<T> เท่านั้นIEnumerable<T> ทุกชนิด

การใช้งานเพิ่มเติม

// รวมจาก List
var set = new HashSet { 1, 2, 3 };
set.UnionWith(new List { 3, 4, 5 }); // {1, 2, 3, 4, 5}

// ตรวจสอบว่ามีการเปลี่ยนแปลงหรือไม่
bool changed = set.UnionWith(other); // คืนค่า true ถ้ามีสมาชิกใหม่เพิ่มเข้ามา (C# 7.3+)