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

HashSet ใน C# (C# Set Collection)

HashSet<T> เป็น Optimized Set Collection — เก็บค่า Unique, Fast Lookup O(1), ไม่รักษาลำดับ ใช้ System.Collections.Generic

คุณสมบัติหลัก

  • ✅ Unique Elements (No Duplicates)
  • ✅ O(1) Average: Add, Remove, Contains
  • ✅ Set Operations: Union, Intersect, Except, SymmetricExcept
  • ❌ No Indexer (ไม่ได้ด้วย Index)
  • ❌ No Order Guarantee (ใช้ SortedSet<T> ถ้าต้องการ Sorted)

การสร้างและใช้งาน

using System.Collections.Generic;

// 1. From Array (Auto Remove Duplicates)
string[] arr = { "one", "two", "two", "one", "three" };
var set = new HashSet(arr);
// set = { "one", "two", "three" }

// 2. Add/Remove
set.Add("four");        // True (Added)
set.Add("one");         // False (Already Exists)
set.Remove("two");      // True (Removed)
set.Remove("missing");  // False (Not Found)

// 3. Lookup
bool hasThree = set.Contains("three"); // True

// 4. Convert to Array/List
string[] uniqueArray = set.ToArray();
List uniqueList = set.ToList();

Set Operations (Mutable — Mutates Current Set)

var setA = new HashSet { 1, 2, 3, 4 };
var setB = new HashSet { 3, 4, 5, 6 };

setA.UnionWith(setB);           // A = {1,2,3,4,5,6}
setA.IntersectWith(setB);       // A = {3,4}
setA.ExceptWith(setB);          // A = {1,2}
setA.SymmetricExceptWith(setB); // A = {1,2,5,6}

Set Operations (Immutable — Returns New, C# 9+ / .NET 6+)

var a = new HashSet { 1, 2, 3 };
var b = new HashSet { 3, 4, 5 };

var union = a.Union(b);           // {1,2,3,4,5}
var intersect = a.Intersect(b);   // {3}
var except = a.Except(b);         // {1,2}
var symmetric = a.SymmetricExcept(b); // {1,2,4,5}

ตัวอย่างครบถ้วน

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

class Program {
    static void Main() {
        string[] arr1 = { "one", "two", "two", "one", "three" };
        
        Console.WriteLine("Original: " + string.Join(", ", arr1));
        // one, two, two, one, three
        
        var hashSet = new HashSet(arr1);
        string[] unique = hashSet.ToArray();
        
        Console.WriteLine("Unique: " + string.Join(", ", unique));
        // one, two, three
        
        // Set Operations Demo
        var setA = new HashSet { 1, 2, 3, 4 };
        var setB = new HashSet { 3, 4, 5, 6 };
        
        var union = new HashSet(setA);
        union.UnionWith(setB);
        Console.WriteLine("Union: " + string.Join(", ", union));
        // 1, 2, 3, 4, 5, 6
        
        Console.ReadKey();
    }
}

HashSet vs Other Collections

HashSet<T>List<T>Dictionary<K,V>SortedSet<T>
Unique✅❌Keys Only✅
Order❌✅ Insertion❌✅ Sorted
ContainsO(1)O(n)O(1) KeyO(log n)
Index Access❌✅❌❌

สรุป

  • ใช้ HashSet<T> เมื่อ: ต้องการ Unique, Fast Lookup, Set Math
  • Constructor รับ IEnumerable<T> → Auto Deduplicate
  • Thread-Unsafe — ใช้ Lock หรือ ImmutableHashSet<T> สำหรับ Multi-thread