C#中如何求两个集合的交集

c#
1197
2024/4/23 10:41:02
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,可以使用LINQ(Language Integrated Query)来求两个集合的交集。下面是一个示例代码:

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 intersection = list1.Intersect(list2);

        foreach (var num in intersection)
        {
            Console.WriteLine(num);
        }
    }
}

在上面的示例中,我们定义了两个整数类型的List集合list1和list2。然后使用Intersect方法来求两个集合的交集,并将结果存储在intersection变量中。最后,使用foreach循环打印出交集的元素。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c# script能实现自定义编辑器吗