要获取C#中HashSet中的元素数,代码如下-
输出结果
这将产生以下输出-
HashSet1中的元素 25 50 75 100 125 150 HashSet1中的元素数 = 6 HashSet2中的元素 30 60 100 150 200 250 HashSet2中的元素数 = 6 它们有共同的元素吗? True HashSet1是否具有元素60? False HashSet2是否具有元素60? True让我们看另一个例子-
using System; using System.Collections.Generic; public class Demo { public static void Main() { HashSet<string> set1 = new HashSet<string>(); set1.Add("AB"); set1.Add("CD"); set1.Add("EF"); set1.Add("AB"); set1.Add("IJ"); set1.Add("KL"); set1.Add("EF"); set1.Add("OP"); Console.WriteLine("HashSet1中的元素"); foreach(string val in set1) { Console.WriteLine(val); } Console.WriteLine("HashSet1中的元素数 = "+set1.Count); HashSet<string> set2 = new HashSet<string>(); set2.Add("EF"); set2.Add("KL"); Console.WriteLine("HashSet2中的元素数 = "+set2.Count); Console.WriteLine("HashSet2中的元素"); foreach(string val in set2) { Console.WriteLine(val); } Console.WriteLine("set1是set2的超集吗? "+set1.IsSupersetOf(set2)); } }输出结果
这将产生以下输出-
HashSet1中的元素 AB CD EF IJ KL OP HashSet1中的元素数 = 6 HashSet2中的元素数 = 2 HashSet2中的元素 EF KL set1是set2的超集吗? True