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

หาค่าที่ซ้ำกันระหว่างลิสต์ใน C# ด้วย Intersect()

Enumerable.Intersect() ใช้หาค่าที่ปรากฏใน ทั้งสอง Sequence (Set Intersection) คืนค่าที่ไม่ซ้ำและเรียงตามลำดับของ Sequence แรก

ลายเซ็น

public static IEnumerable<TSource> Intersect<TSource>(
    this IEnumerable<TSource> first,
    IEnumerable<TSource> second,
    IEqualityComparer<TSource> comparer = null);

ตัวอย่างพื้นฐาน

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

public class Demo
{
    public static void Main()
    {
        var list1 = new List { 3, 4 };
        var list2 = new List { 1, 2, 3 };

        var common = list1.Intersect(list2);

        Console.WriteLine("Common values:");
        foreach (int n in common)
            Console.WriteLine(n);  // แสดงแค่ 3
    }
}

ผลลัพธ์

3

Intersect กับ Object/Class (ต้องใช้ Comparer)

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

var products1 = new List
{
    new Product { Id = 1, Name = "Laptop" },
    new Product { Id = 2, Name = "Mouse" }
};

var products2 = new List
{
    new Product { Id = 2, Name = "Mouse" },
    new Product { Id = 3, Name = "Keyboard" }
};

// ต้องใช้ Custom Comparer
var common = products1.Intersect(products2, new ProductComparer());

public class ProductComparer : IEqualityComparer
{
    public bool Equals(Product x, Product y) => x.Id == y.Id;
    public int GetHashCode(Product obj) => obj.Id.GetHashCode();
}

Intersect หลายลิสต์

var common = list1
    .Intersect(list2)
    .Intersect(list3)
    .Intersect(list4);

ประสิทธิภาพ

  • ใช้ HashSet ภายใน → O(n + m) โดยเฉลี่ย
  • Deferred Execution - คำนวณตอน Iterate
  • สำหรับข้อมูลใหญ่ ควร ToList() ก่อนถ้าใช้ซ้ำหลายครั้ง

กรณีใช้งานจริง

  • หาสินค้าที่ลูกค้าซื้อร่วมกัน (Market Basket Analysis)
  • หา User ที่ใช้ Feature ทั้งสอง (Feature Adoption)
  • Validation: ตรวจสอบ ID ที่มีในทั้งสองระบบ
  • Security: หา Permission ที่ User มีและ Role ต้องการ

ข้อควรระวัง

Intersect() จะคืนค่า Distinct เสมอ - ถ้า list1 มี [1, 1, 2] และ list2 มี [1] ผลลัพธ์คือ [1] เพียงค่าเดียว