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

เมธอด Intersect ของ C# LINQ

หาองค์ประกอบร่วมระหว่างสองอาร์เรย์โดยใช้เมธอด Intersect()

นี่คืออาร์เรย์ของเรา:

int[] val1 = { 15, 20, 40, 60, 75, 90 };
int[] val2 = { 17, 25, 35, 55, 75, 90 };

เพื่อทำการหาส่วนร่วม (intersection):

val1.AsQueryable().Intersect(val2);

มาดูตัวอย่างทั้งหมดกัน

ตัวอย่าง

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

class Demo
{
    static void Main()
    {
        int[] val1 = { 15, 20, 40, 60, 75, 90 };
        int[] val2 = { 17, 25, 35, 55, 75, 90 };
        
        IEnumerable<int> res = val1.AsQueryable().Intersect(val2);
        Console.WriteLine("Intersection of both the lists...");
        foreach (int a in res)
            Console.WriteLine(a);
    }
}

ผลลัพธ์

Intersection of both the lists...
75
90