c#

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

小亿
174
2024-04-02 10:41:02
栏目: 编程语言

在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循环打印出交集的元素。

0
看了该问题的人还看了