温馨提示×

C#中如何用Intersect求两个对象列表的交集

c#
小亿
96
2024-04-02 14:11:02
栏目: 编程语言

在C#中,可以使用LINQ的Intersect方法来求两个对象列表的交集。以下是一个示例代码:

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

class Program
{
    static void Main()
    {
        List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };
        List<int> list2 = new List<int> { 3, 4, 5, 6, 7 };

        var intersect = list1.Intersect(list2);

        foreach (var item in intersect)
        {
            Console.WriteLine(item);
        }
    }
}

上面的示例代码中,通过调用list1的Intersect方法并传入list2作为参数,就可以得到两个列表的交集。最后,利用foreach循环打印出交集元素。

0