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

การสร้าง HashSet ใน C# (Initializing HashSet)

HashSet<T> เป็น Collection ที่เก็บค่า ไม่ซ้ำกัน (Unique) และมี Performance O(1) สำหรับ Lookup/Add/Remove ใช้ System.Collections.Generic

การสร้างและ Initialize

1. ว่าง แล้ว Add ทีละตัว

var set = new HashSet();
set.Add("electronics");
set.Add("accessories");
set.Add("electronics"); // Duplicate — จะถูกเพิกเฉย

2. จาก Collection อื่น (Constructor)

string[] arr = { "electronics", "accessories", "electronics", "clothing" };
var set = new HashSet(arr); // Duplicate ถูกกำจัดอัตโนมัติ
// set = { "electronics", "accessories", "clothing" }

3. Collection Expression (C# 12+)

HashSet set = new() { "electronics", "accessories", "clothing" };

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

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

class Program {
    static void Main() {
        string[] arr1 = { "electronics", "accessories", "electronics" };
        
        Console.WriteLine("Original Array: " + string.Join(", ", arr1));
        // Output: electronics, accessories, electronics
        
        // สร้าง HashSet จาก Array
        var hashSet = new HashSet(arr1);
        
        // แปลงกลับเป็น Array (Unique)
        string[] uniqueArr = hashSet.ToArray();
        Console.WriteLine("Unique Array: " + string.Join(", ", uniqueArr));
        // Output: electronics, accessories
        
        // ตรวจสอบการมีอยู่
        Console.WriteLine($"Contains 'electronics': {hashSet.Contains("electronics")}"); // True
        Console.WriteLine($"Contains 'books': {hashSet.Contains("books")}"); // False
        
        // Set Operations
        var set2 = new HashSet { "accessories", "books", "toys" };
        hashSet.UnionWith(set2);        // Union
        hashSet.IntersectWith(set2);    // Intersection
        hashSet.ExceptWith(set2);       // Difference
        hashSet.SymmetricExceptWith(set2); // Symmetric Difference
        
        Console.ReadKey();
    }
}

เมธอดสำคัญ

MethodคำอธิบายComplexity
Add(T)เพิ่มถ้ายังไม่มี คืน boolO(1)
Remove(T)ลบถ้ามี คืน boolO(1)
Contains(T)ตรวจสอบสมาชิกO(1)
Clear()ลบทั้งหมดO(n)
UnionWithUnion (ในที่นี้ Mutates)O(n)
IntersectWithIntersectionO(n)
ExceptWithDifference (A - B)O(n)
IsSubsetOf / IsSupersetOfSubset/Superset CheckO(n)
Overlapsมีสมาชิกร่วมกันไหมO(n)
SetEqualsสมาชิกเหมือนกันหมดไหมO(n)

HashSet vs List vs Dictionary

HashSet<T>List<T>Dictionary<TKey, TValue>
Unique Values✅ Yes❌ No✅ Keys Only
Order Preserved❌ No✅ Yes❌ No (OrderedDict: Yes)
Lookup SpeedO(1)O(n)O(1)
Key-Value❌❌✅

สรุป

  • ใช้ HashSet<T> เมื่อต้องการ Unique Collection + Fast Lookup
  • Constructor รับ IEnumerable<T> → กำจัด Duplicate อัตโนมัติ
  • ไม่รักษาลำดับ — ถ้าต้องการ Ordered Unique ใช้ SortedSet<T> หรือ ImmutableHashSet<T>