检查 HashSet 是否是 C# 中指定集合的一个真子集
如要检查 HashSet 是否是指定集合的真子集,请尝试以下代码 −
示例
using System; using System.Collections.Generic; public class Demo { public static void Main(){ HashSet<int> set1 = new HashSet<int>(); set1.Add(70); set1.Add(100); set1.Add(125); set1.Add(150); Console.WriteLine("Elements in HashSet1"); foreach(int val in set1){ Console.WriteLine(val); } HashSet<int> set2 = new HashSet<int>(); set2.Add(30); set2.Add(60); set2.Add(70); set2.Add(80); set2.Add(100); set2.Add(125); set2.Add(150); set2.Add(200); Console.WriteLine("Elements in HashSet2"); foreach(int val in set2){ Console.WriteLine(val); } Console.WriteLine("Is set1 a proper subset of set2? "+set1.IsProperSubsetOf(set2)); } }
输出
这将产生以下输出 −
Elements in HashSet1 70 100 125 150 Elements in HashSet2 30 60 70 80 100 125 150 200 Is set1 a proper subset of set2? True
示例
现在我们来看另一个示例 −
using System; using System.Collections.Generic; public class Demo { public static void Main(){ HashSet<int> set1 = new HashSet<int>(); set1.Add(10); set1.Add(20); Console.WriteLine("Elements in HashSet1"); foreach(int val in set1){ Console.WriteLine(val); } HashSet<int> set2 = new HashSet<int>(); set2.Add(30); set2.Add(60); set2.Add(70); set2.Add(80); set2.Add(100); set2.Add(125); set2.Add(150); set2.Add(200); Console.WriteLine("Elements in HashSet2"); foreach(int val in set2){ Console.WriteLine(val); } Console.WriteLine("Is set1 a proper subset of set2? "+set1.IsProperSubsetOf(set2)); } }
输出
这将产生以下输出 −
Elements in HashSet1 10 20 Elements in HashSet2 30 60 70 80 100 125 150 200 Is set1 a proper subset of set2?False
广告