ใน C# คุณสามารถได้รับ Enumerator เพื่อวนลูปผ่านสมาชิกของ HashSet<T> ได้สองวิธีหลัก ได้แก่การใช้ foreach (ซึ่งใช้ Enumerator ภายในโดยอัตโนมัติ) หรือเรียก GetEnumerator() โดยตรงเพื่อควบคุมการวนลูปได้ละเอียดขึ้น
ตัวอย่างโค้ด
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main(string[] args)
{
// HashSet แรก - ใช้ foreach
HashSet set1 = new HashSet();
set1.Add("A");
set1.Add("B");
set1.Add("C");
set1.Add("D");
set1.Add("E");
set1.Add("F");
set1.Add("G");
set1.Add("H");
Console.WriteLine("Elements in HashSet1...");
foreach (string res in set1)
{
Console.WriteLine(res);
}
// HashSet ที่สอง - ใช้ Enumerator โดยตรง
HashSet set2 = new HashSet();
set2.Add("John");
set2.Add("Jacob");
set2.Add("Ryan");
set2.Add("Tom");
set2.Add("Andy");
set2.Add("Tim");
set2.Add("Steve");
set2.Add("Mark");
Console.WriteLine("Elements in HashSet2... (Enumerator iterating through HashSet)");
HashSet.Enumerator demoEnum = set2.GetEnumerator();
while (demoEnum.MoveNext())
{
string res = demoEnum.Current;
Console.WriteLine(res);
}
Console.WriteLine("Is HashSet1 equal to HashSet2? = " + set1.Equals(set2));
Console.WriteLine("Count of HashSet2 = " + set2.Count);
set2.Clear();
Console.WriteLine("Count of HashSet2 (updated) = " + set2.Count);
}
}
ผลลัพธ์
Elements in HashSet1...
A
B
C
D
E
F
G
H
Elements in HashSet2... (Enumerator iterating through HashSet)
John
Jacob
Ryan
Tom
Andy
Tim
Steve
Mark
Is HashSet1 equal to HashSet2? = False
Count of HashSet2 = 8
Count of HashSet2 (updated) = 0
ตัวอย่างเพิ่มเติม: การจัดการค่าซ้ำและ Superset
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
// HashSet จะเก็บค่าที่ไม่ซ้ำกันโดยอัตโนมัติ
HashSet set1 = new HashSet();
set1.Add("AB");
set1.Add("CD");
set1.Add("EF");
set1.Add("AB"); // ซ้ำ - จะถูกเพิกเฉย
set1.Add("IJ");
set1.Add("KL");
set1.Add("EF"); // ซ้ำ - จะถูกเพิกเฉย
set1.Add("OP");
Console.WriteLine("Elements in HashSet1");
foreach (string val in set1)
{
Console.WriteLine(val);
}
HashSet set2 = new HashSet();
set2.Add("EF");
set2.Add("KL");
Console.WriteLine("Elements in HashSet2... (Enumerator iterating through HashSet)");
HashSet.Enumerator demoEnum = set2.GetEnumerator();
while (demoEnum.MoveNext())
{
string res = demoEnum.Current;
Console.WriteLine(res);
}
// ตรวจสอบว่า set1 เป็น superset ของ set2 หรือไม่
Console.WriteLine("Is set1 a superset of set2? " + set1.IsSupersetOf(set2));
}
}
ผลลัพธ์
Elements in HashSet1
AB
CD
EF
IJ
KL
OP
Elements in HashSet2... (Enumerator iterating through HashSet)
EF
KL
Is set1 a superset of set2? True
สรุป
HashSet<T>เก็บค่าที่ ไม่ซ้ำกัน (unique values) โดยอัตโนมัติ- ใช้
GetEnumerator()เพื่อรับ Enumerator ควบคุมการวนลูปด้วยตนเอง - รองรับ operation เซต เช่น
IsSupersetOf,IsSubsetOf,UnionWith,IntersectWith,ExceptWith - ประสิทธิภาพ O(1) สำหรับการเพิ่ม ลบ และค้นหา
- ไม่รักษาลำดับของข้อมูล (unordered)