Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức Intersect() trong C# LINQ

Intersect() trả về giao của hai chuỗi - các phần tử xuất hiện trong cả hai chuỗi. Loại bỏ trùng lặp, không bảo đảm thứ tự.

Ví dụ minh họa

Hai mảng int:

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

Tìm phần tử chung:

IEnumerable<int> res = val1.AsQueryable().Intersect(val2);

Mã nguồn hoàn chỉnh

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("Giao của hai danh sách...");
        foreach (int a in res)
            Console.WriteLine(a);
    }
}

Kết quả đầu ra

Giao của hai danh sách...
75
90

Lưu ý: Dùng IntersectBy() (.NET 6+) để giao theo key selector. Để giữ thứ tự, dùng val1.Where(x => val2.Contains(x)).Distinct().