📅  最后修改于: 2023-12-03 15:30:18.057000             🧑  作者: Mango
在编程中,SortedSet 和其他集合类型一样,用于存储一组相同类型的元素。SortedSet 与其他集合的区别在于,它按照元素的值进行排序,并且集合中不允许存在重复元素。在本文中,我们将探讨如何检查 SortedSet 和指定的集合是否共享公共元素。
我们可以使用 Linq 中的 Intersect() 方法来检查 SortedSet 和指定的集合是否有共同的元素。下面是一个示例:
using System;
using System.Linq;
class Program
{
static void Main()
{
SortedSet<int> set1 = new SortedSet<int> { 1, 2, 3 };
int[] arr = { 2, 4, 5 };
var common = set1.Intersect(arr);
foreach (int element in common)
Console.WriteLine(element);
}
}
在上面的示例中,我们创建了一个 SortedSet
与上面的示例不同,我们需要对指定的集合调用 Intersect() 方法。下面是示例:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
SortedSet<int> set1 = new SortedSet<int> { 1, 2, 3 };
List<int> list1 = new List<int> { 2, 4, 5 };
var common = list1.Intersect(set1);
foreach (int element in common)
Console.WriteLine(element);
}
}
在上面的示例中,我们创建了一个 SortedSet
在本文中,我们学习了如何使用 Intersect() 方法检查 SortedSet 和其他集合是否共享公共元素。请记住,在使用 Intersect() 方法之前,必须先引用 System.Linq 命名空间。