Giới thiệu
HashSet<T> (namespace System.Collections.Generic) là tập hợp không trùng lặp, không sắp xếp, hiệu suất O(1) cho Add/Contains/Remove. Phương thức UnionWith() thực hiện phép hợp tập hợp (union).
Ví dụ 1: Hợp nhất hai HashSet giống nhau
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet<int> set1 = new HashSet<int>();
set1.Add(100);
set1.Add(200);
set1.Add(300);
set1.Add(400);
set1.Add(500);
set1.Add(600);
Console.WriteLine("HashSet1 elements...");
foreach (int ele in set1)
{
Console.WriteLine(ele);
}
HashSet<int> set2 = new HashSet<int>();
set2.Add(100);
set2.Add(200);
set2.Add(300);
set2.Add(400);
set2.Add(500);
set2.Add(600);
Console.WriteLine("HashSet2 elements...");
foreach (int ele in set2)
{
Console.WriteLine(ele);
}
Console.WriteLine("Union...");
set1.UnionWith(set2);
foreach (int ele in set1)
{
Console.WriteLine(ele);
}
}
}
Kết quả
HashSet1 elements... 100 200 300 400 500 600 HashSet2 elements... 100 200 300 400 500 600 Union... 100 200 300 400 500 600
Ví dụ 2: Hợp nhất hai HashSet khác nhau
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet<int> set1 = new HashSet<int>();
set1.Add(100);
set1.Add(200);
set1.Add(300);
set1.Add(400);
set1.Add(500);
set1.Add(600);
Console.WriteLine("HashSet1 elements...");
foreach (int ele in set1)
{
Console.WriteLine(ele);
}
HashSet<int> set2 = new HashSet<int>();
set2.Add(100);
set2.Add(250);
set2.Add(300);
Console.WriteLine("HashSet2 elements...");
foreach (int ele in set2)
{
Console.WriteLine(ele);
}
Console.WriteLine("Union...");
set1.UnionWith(set2);
foreach (int ele in set1)
{
Console.WriteLine(ele);
}
}
}
Kết quả
HashSet1 elements... 100 200 300 400 500 600 HashSet2 elements... 100 250 300 Union... 100 200 250 300 400 500 600
Các phép toán tập hợp của HashSet
UnionWith(other)- Hợp (A ∪ B)IntersectWith(other)- Giao (A ∩ B)ExceptWith(other)- Hiệu (A \ B)SymmetricExceptWith(other)- Hiệu đối xứng (A Δ B)IsSubsetOf(other)- Là tập conIsSupersetOf(other)- Là tập chaIsProperSubsetOf(other)- Là tập con thực sựIsProperSupersetOf(other)- Là tập cha thực sựOverlaps(other)- Có giao nhauSetEquals(other)- Bằng nhau
HashSet vs SortedSet
| Đặc điểm | HashSet<T> | SortedSet<T> |
|---|---|---|
| Thứ tự | Không đảm bảo | Tự động sắp xếp |
| Phức tạp Add/Contains | O(1) trung bình | O(log n) |
| Yêu cầu T | GetHashCode, Equals | IComparable<T> |