Mục đích
Phương thức HashSet<T>.IntersectWith(IEnumerable<T> other) **sửa đổi HashSet hiện tại** để chỉ giữ lại các phần tử **cũng có trong** other (giao - intersection). Trả về void.
Ví dụ 1: Giao hai HashSet
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet set1 = new HashSet();
set1.Add("AB"); set1.Add("CD"); set1.Add("EF");
set1.Add("AB"); // Duplicate, bị bỏ qua
set1.Add("IJ"); set1.Add("KL"); set1.Add("EF"); set1.Add("OP");
HashSet set2 = new HashSet();
set2.Add("EF"); set2.Add("KL");
Console.WriteLine("Set1 ban đầu:");
foreach (string s in set1) Console.WriteLine(s);
Console.WriteLine("\nSet2:");
foreach (string s in set2) Console.WriteLine(s);
// Kiểm tra superset trước khi intersect
Console.WriteLine($"\nSet1 là superset của Set2? {set1.IsSupersetOf(set2)}"); // True
// Thực hiện giao (thay đổi set1)
set1.IntersectWith(set2);
Console.WriteLine("\nKết quả Intersection (set1 đã thay đổi):");
foreach (string s in set1) Console.WriteLine(s);
}
}
Kết quả
Set1 ban đầu:
AB
CD
EF
IJ
KL
OP
Set2:
EF
KL
Set1 là superset của Set2? True
Kết quả Intersection (set1 đã thay đổi):
EF
KL
Ví dụ 2: Giao hai HashSet giống hệt nhau
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet set1 = new HashSet { 30, 60, 70, 80, 100, 125 };
HashSet set2 = new HashSet { 30, 60, 70, 80, 100, 125 };
Console.WriteLine("Set1:");
foreach (int v in set1) Console.WriteLine(v);
Console.WriteLine("\nSet2:");
foreach (int v in set2) Console.WriteLine(v);
set1.IntersectWith(set2);
Console.WriteLine("\nIntersection result:");
foreach (int v in set1) Console.WriteLine(v);
}
}
Kết quả
Set1:
30
60
70
80
100
125
Set2:
30
60
70
80
100
125
Intersection result:
30
60
70
80
100
125
Các phương thức liên quan (Set Operations)
| Phương thức | Mô tả | Thay đổi this? |
|---|---|---|
IntersectWith | Giao (chỉ giữ phần chung) | Có |
UnionWith | Hợp (gộp tất cả) | Có |
ExceptWith | Hiệu (loại bỏ phần trong other) | Có |
SymmetricExceptWith | Đối xứng (chỉ giữ phần khác nhau) | Có |
IsSubsetOf | Kiểm tra con | Không |
IsSupersetOf | Kiểm tra cha | Không |
Overlaps | Có phần tử chung? | Không |
SetEquals | Bằng nhau? | Không |
Lưu ý
IntersectWith**thay đổi set gốc**. Nếu cần giữ nguyên, hãy clone trước:var copy = new HashSet<T>(set1); copy.IntersectWith(set2);- Phức tạp: O(n) với n = số phần tử trong set nhỏ hơn (nếu other là HashSet cùng comparer).
- HashSet không giữ thứ tự. Nếu cần thứ tự, dùng
SortedSet.