温馨提示×

LINQ怎么求两个对象列表的交集

小亿
92
2024-04-02 14:09:56
栏目: 编程语言

在LINQ中,可以使用Intersect方法来求两个对象列表的交集。示例如下:

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

var intersectList = list1.Intersect(list2).ToList();

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

在上面的示例中,Intersect方法会返回list1list2中相同的元素,即交集。最终输出结果为:

3
4
5

0