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

Kiểm tra 2 List có phần tử chung trong C#

Kiểm tra 2 tập hợp có giao nhau: dùng HashSet.IntersectWith, LINQ Intersect, hoặc Any với Contains.

Ví dụ minh họa

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] arr1 = { 65, 57, 63, 98 };
        int[] arr2 = { 43, 65, 33, 57 };
        
        // Cách 1: LINQ Intersect (trả về các phần tử chung)
        var common = arr1.Intersect(arr2).ToList();
        Console.WriteLine($"Phần tử chung (Intersect): {string.Join(", ", common)}");
        Console.WriteLine($"Có phần tử chung? {common.Any()}");
        
        // Cách 2: HashSet - hiệu năng tốt cho tập lớn
        var set1 = new HashSet(arr1);
        var set2 = new HashSet(arr2);
        set1.IntersectWith(set2); // Sửa đổi set1
        Console.WriteLine($"HashSet IntersectWith: {string.Join(", ", set1)}");
        
        // Cách 3: Any + Contains (dừng sớm khi tìm thấy 1)
        bool hasCommon = arr1.Any(x => arr2.Contains(x));
        Console.WriteLine($"Any+Contains: {hasCommon}");
        
        // Cách 4: HashSet + Any (O(1) lookup)
        var hs = new HashSet(arr2);
        bool hasCommonFast = arr1.Any(x => hs.Contains(x));
        Console.WriteLine($"HashSet+Any: {hasCommonFast}");
    }
}

Kết quả đầu ra

Phần tử chung (Intersect): 65, 57
Có phần tử chung? True
HashSet IntersectWith: 65, 57
Any+Contains: True
HashSet+Any: True

Hiệu năng: Any+Contains trên mảng: O(n×m). HashSet+Any: O(n+m). Intersect: O(n+m) nhưng tạo tập kết quả. Chỉ cần true/false → dùng HashSet+Any.