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

หาค่าร่วมของสองรายการใน C#

ใช้เมธอด Intersect() ของ LINQ เพื่อหาองค์ประกอบที่ปรากฏใน ทั้งสอง ลำดับ (Set Intersection)

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

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

class Demo
{
    static void Main()
    {
        List val1 = new List { 25, 30, 40, 60, 80, 95, 110 };
        List val2 = new List { 27, 35, 40, 75, 95, 100, 110 };

        IEnumerable res = val1.AsQueryable().Intersect(val2);

        Console.WriteLine("Intersection of both lists...");
        foreach (int a in res) Console.WriteLine(a);
    }
}

ผลลัพธ์

Intersection of both lists...
40
95
110

หมายเหตุ: ผลลัพธ์ไม่มีค่าซ้ำ และลำดับขึ้นกับการ implement ของ Intersect (โดยทั่วไปคือลำดับของลำดับแรก)