Giới thiệu
Phương thức IsProperSubsetOf() của HashSet<T> kiểm tra xem tập hợp hiện tại có phải là tập con thực sự (proper subset) của tập hợp chỉ định hay không. Tức là tất cả phần tử của tập hợp hiện tại đều nằm trong tập hợp chỉ định và tập hợp chỉ định có ít nhất một phần tử không nằm trong tập hợp hiện tại.
Ví dụ 1
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet set1 = new HashSet();
set1.Add(70);
set1.Add(100);
set1.Add(125);
set1.Add(150);
Console.WriteLine("Các phần tử trong HashSet1:");
foreach (int val in set1)
{
Console.WriteLine(val);
}
HashSet set2 = new HashSet();
set2.Add(30);
set2.Add(60);
set2.Add(70);
set2.Add(80);
set2.Add(100);
set2.Add(125);
set2.Add(150);
set2.Add(200);
Console.WriteLine("Các phần tử trong HashSet2:");
foreach (int val in set2)
{
Console.WriteLine(val);
}
Console.WriteLine("set1 là tập con thực sự của set2? " + set1.IsProperSubsetOf(set2));
}
}
Kết quả
Các phần tử trong HashSet1 70 100 125 150 Các phần tử trong HashSet2 30 60 70 80 100 125 150 200 set1 là tập con thực sự của set2? True
Ví dụ 2
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet set1 = new HashSet();
set1.Add(10);
set1.Add(20);
Console.WriteLine("Các phần tử trong HashSet1:");
foreach (int val in set1)
{
Console.WriteLine(val);
}
HashSet set2 = new HashSet();
set2.Add(30);
set2.Add(60);
set2.Add(70);
set2.Add(80);
set2.Add(100);
set2.Add(125);
set2.Add(150);
set2.Add(200);
Console.WriteLine("Các phần tử trong HashSet2:");
foreach (int val in set2)
{
Console.WriteLine(val);
}
Console.WriteLine("set1 là tập con thực sự của set2? " + set1.IsProperSubsetOf(set2));
}
}
Kết quả
Các phần tử trong HashSet1 10 20 Các phần tử trong HashSet2 30 60 70 80 100 125 150 200 set1 là tập con thực sự của set2? False
Lưu ý quan trọng
- Tập con thực sự (Proper Subset): A ⊂ B ⇔ A ⊆ B VÀ A ≠ B.
- Nếu hai HashSet bằng nhau,
IsProperSubsetOf()trả vềfalse. - Phương thức
IsSubsetOf()(không có "Proper") trả vềtruenếu A ⊆ B (cho phép A = B). HashSetkhông duy trì thứ tự, tìm kiếm O(1) trung bình.- Phần tử phải override
GetHashCode()vàEquals()chính xác cho kiểu tự định nghĩa.