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) | เพิ่มถ้ายังไม่มี คืน bool | O(1) |
Remove(T) | ลบถ้ามี คืน bool | O(1) |
Contains(T) | ตรวจสอบสมาชิก | O(1) |
Clear() | ลบทั้งหมด | O(n) |
UnionWith | Union (ในที่นี้ Mutates) | O(n) |
IntersectWith | Intersection | O(n) |
ExceptWith | Difference (A - B) | O(n) |
IsSubsetOf / IsSupersetOf | Subset/Superset Check | O(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 Speed | O(1) | O(n) | O(1) |
| Key-Value | ❌ | ❌ | ✅ |
สรุป
- ใช้
HashSet<T> เมื่อต้องการ Unique Collection + Fast Lookup
- Constructor รับ
IEnumerable<T> → กำจัด Duplicate อัตโนมัติ
- ไม่รักษาลำดับ — ถ้าต้องการ Ordered Unique ใช้
SortedSet<T> หรือ ImmutableHashSet<T>