在C#中,你可以使用LINQ(Language Integrated Query)来实现集合的交集操作。以下是一个简单的示例:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// 创建两个集合
List<int> set1 = new List<int> { 1, 2, 3, 4, 5 };
List<int> set2 = new List<int> { 4, 5, 6, 7, 8 };
// 使用LINQ实现交集操作
var intersection = set1.Intersect(set2);
// 输出结果
Console.WriteLine("交集为:");
foreach (var item in intersection)
{
Console.Write(item + " ");
}
}
}
在这个示例中,我们创建了两个整数列表set1
和set2
,然后使用Intersect
方法计算它们的交集。最后,我们遍历并输出交集中的元素。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: c#事件与委托的使用场景是什么