Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Giao của hai HashSet trong C#

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ứcMô tảThay đổi this?
IntersectWithGiao (chỉ giữ phần chung)Có
UnionWithHợp (gộp tất cả)Có
ExceptWithHiệu (loại bỏ phần trong other)Có
SymmetricExceptWithĐối xứng (chỉ giữ phần khác nhau)Có
IsSubsetOfKiểm tra conKhông
IsSupersetOfKiểm tra chaKhông
OverlapsCó phần tử chung?Không
SetEqualsBằ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.