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

Phương thức Intersect trong C#

Sử dụng Intersect để lấy phần tử chung.

Tạo List:

var list1 = new List<int> { 99, 87 };
var list2 = new List<int> { 56, 87, 45, 99 };

Lấy giao:

var res = list1.Intersect(list2);

Ví dụ hoàn chỉnh

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

public class Demo
{
    public static void Main()
    {
        var list1 = new List<int> { 99, 87 };
        var list2 = new List<int> { 56, 87, 45, 99 };
        
        var res = list1.Intersect(list2);
        
        foreach (int i in res)
        {
            Console.WriteLine(i);
        }
    }
}

Kết quả

99
87

Lưu ý: Intersect trả về tập hợp không trùng lặp, thứ tự không đảm bảo. Cần using System.Linq;. Hoạt động trên bất kỳ IEnumerable<T>.