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

Intersection ของสองอาร์เรย์ใน C#

หาส่วนร่วม (Intersection) ของสองอาร์เรย์ใน C#

ใช้ Extension Method Intersect จาก System.Linq คืนค่าสมาชิกที่มีในทั้งสองอาร์เรย์ (Unique Values)

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


using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] arr1 = { 44, 76, 98, 34 };
        int[] arr2 = { 24, 98, 44, 55, 47, 86 };
        
        var intersection = arr1.Intersect(arr2);
        
        foreach (int val in intersection)
            Console.WriteLine(val);
    }
}

ผลลัพธ์


44
98

รายละเอียดสำคัญ

  • Distinct: ผลลัพธ์ไม่มีค่าซ้ำ (Set Intersection)
  • Order: ตามลำดับใน Array แรก (arr1)
  • Deferred Execution: Query ไม่รันจนกว่าจะ Enumerate (foreach, ToList)
  • Custom Comparer: ใช้ Overload Intersect(second, comparer) สำหรับ Object/Case-Insensitive String

ตัวอย่าง: String Case-Insensitive


string[] a = { "Apple", "Banana", "Cherry" };
string[] b = { "apple", "BANANA", "Durian" };

var result = a.Intersect(b, StringComparer.OrdinalIgnoreCase);
// "Apple", "Banana"

ตัวอย่าง: Object ด้วย Key Selector (Custom)


class Person { public int Id; public string Name; }

var list1 = new[] { new Person{Id=1, Name="A"}, new Person{Id=2, Name="B"} };
var list2 = new[] { new Person{Id=2, Name="B"}, new Person{Id=3, Name="C"} };

// Intersect โดยเปรียบเทียบ Id
var common = list1.Where(p1 => list2.Any(p2 => p2.Id == p1.Id));
// หรือสร้าง IEqualityComparer

เมธอด LINQ Set Operations อื่นๆ

เมธอดคำอธิบายSQL เทียบเท่า
Intersectส่วนร่วม (AND)INTERSECT
Unionรวมไม่ซ้ำ (OR)UNION
Exceptอยู่ในตัวแรก ไม่อยู่ในตัวหลัง (A-B)EXCEPT
Concatต่อท้าย (เก็บซ้ำได้)UNION ALL