在 C# 中向 HashSet 添加元素
csharpserver side programmingprogramming更新于 2025/9/11 11:13:00
要将元素添加到 HashSet,代码如下 −
示例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
HashSet<string> set1 = new HashSet<string>();
set1.Add("A");
set1.Add("B");
set1.Add("C");
set1.Add("D");
set1.Add("E");
set1.Add("F");
set1.Add("G");
set1.Add("H");
Console.WriteLine("Elements in HashSet1...");
foreach (string res in set1){
Console.WriteLine(res);
}
HashSet<string> set2 = new HashSet<string>();
set2.Add("John");
set2.Add("Jacob");
set2.Add("Ryan");
set2.Add("Tom");
set2.Add("Andy");
set2.Add("Tim");
set2.Add("Steve");
set2.Add("Mark");
Console.WriteLine("HashSet2 中的元素... (遍历 HashSet 的枚举器)");
HashSet<string>.Enumerator demoEnum = set2.GetEnumerator();
while (demoEnum.MoveNext()) {
string res = demoEnum.Current;
Console.WriteLine(res);
}
Console.WriteLine("HashSet1 是否等于 HashSet2? = "+set1.Equals(set2));
}
}
输出
将产生以下输出 −
HashSet1 中的元素... A B C D E F G H HashSet2 中的元素... (遍历 HashSet 的枚举器) John Jacob Ryan Tom Andy Tim Steve Mark HashSet1 是否等于 HashSet2? = False HashSet2 的计数 = 8 HashSet2 的计数(已更新) = 0
示例
现在让我们看另一个示例 −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
HashSet<int> set1 = new HashSet<int>();
set1.Add(100);
set1.Add(200);
Console.WriteLine("HashSet1 中的元素...");
foreach (int res in set1){
Console.WriteLine(res);
}
HashSet<int> set2 = new HashSet<int>();
set2.Add(100);
set2.Add(200);
Console.WriteLine("HashSet2 中的元素...");
foreach (int res in set2){
Console.WriteLine(res);
}
Console.WriteLine("set1 是 set2 的子集吗?"+set1.IsSubsetOf(set2));
}
}
输出
将产生以下输出 −
HashSet1 中的元素... 100 200 HashSet2 中的元素... 100 200 set1 是 set2 的子集吗?True

