Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตรวจสอบว่าสอง List มี Element ซ้ำกันหรือไม่ใน C#

ภาพรวม

ใช้ HashSet<T> และ LINQ Intersect หรือ Any เพื่อตรวจสอบว่าสอง Collection มีสมาชิกร่วมกันหรือไม่

โค้ดตัวอย่าง


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

public class Program {
    public static void Main() {
        int[] arr1 = { 65, 57, 63, 98 };
        int[] arr2 = { 43, 65, 33, 57 };

        Console.WriteLine($"Array 1: [{string.Join(", ", arr1)}]");
        Console.WriteLine($"Array 2: [{string.Join(", ", arr2)}]");

        // วิธีที่ 1: HashSet + Any (เร็วที่สุด O(n+m))
        var set2 = new HashSet<int>(arr2);
        bool hasCommon = arr1.Any(x => set2.Contains(x));
        Console.WriteLine($"Has common elements: {hasCommon}"); // True

        // วิธีที่ 2: LINQ Intersect (สร้าง collection ใหม่)
        var common = arr1.Intersect(arr2).ToArray();
        Console.WriteLine($"Common elements: [{string.Join(", ", common)}]"); // 65, 57

        // วิธีที่ 3: Manual Two-pointer (ต้อง Sorted ก่อน)
        Array.Sort(arr1);
        Array.Sort(arr2);

        int i = 0, j = 0;
        var commonManual = new List<int>();
        while (i < arr1.Length && j < arr2.Length) {
            if (arr1[i] == arr2[j]) {
                commonManual.Add(arr1[i]);
                i++; j++;
            } else if (arr1[i] < arr2[j]) {
                i++;
            } else {
                j++;
            }
        }
        Console.WriteLine($"Common (manual): [{string.Join(", ", commonManual)}]");
    }
}

ผลลัพธ์


Array 1: [65, 57, 63, 98]
Array 2: [43, 65, 33, 57]
Has common elements: True
Common elements: [65, 57]
Common (manual): [57, 65]

Performance Comparison

MethodTime ComplexitySpaceReturns
HashSet + AnyO(n + m)O(m)bool (มีร่วมหรือไม่)
LINQ IntersectO(n + m)O(min(n,m))Common elements
Two Pointer (Sorted)O(n log n + m log m)O(1) extraCommon elements (sorted)
Nested LoopO(n × m)O(1)Common elements

Extension Method สำหรับ Reusability


public static class CollectionExtensions {
    public static bool HasCommonElements<T>(
        this IEnumerable<T> first,
        IEnumerable<T> second,
        IEqualityComparer<T> comparer = null) {
        var set = new HashSet<T>(second, comparer);
        return first.Any(set.Contains);
    }

    public static IEnumerable<T> GetCommonElements<T>(
        this IEnumerable<T> first,
        IEnumerable<T> second) {
        var set = new HashSet<T>(second);
        return first.Where(set.Contains);
    }
}

// ใช้งาน
bool hasCommon = arr1.HasCommonElements(arr2);
var common = arr1.GetCommonElements(arr2).ToList();