从C#中的HashSet中删除集合中的所有元素
要从HashSet中删除集合中的所有元素,代码如下-
示例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
HashSet<string> set1 = new HashSet<string>();
set1.Add("Ryan");
set1.Add("Tom");
set1.Add("Andy");
set1.Add("Tim");
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("Elements in HashSet2...");
foreach (string res in set2){
Console.WriteLine(res);
}
Console.WriteLine("Is HashSet1 equal to HashSet2? = "+set1.Equals(set2));
set2.ExceptWith(set1);
//显示set2中不在set1上的元素
foreach(string i in set2){
Console.WriteLine(i);
}
}
}输出结果
这将产生以下输出-
Elements in HashSet1... Ryan Tom Andy Tim Elements in HashSet2... John Jacob Ryan Tom Andy Tim Steve Mark Is HashSet1 equal to HashSet2? = False John Jacob Steve Mark
示例
让我们看另一个例子-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
HashSet<string> set1 = new HashSet<string>();
set1.Add("Jacob");
set1.Add("Ryan");
set1.Add("Tom");
set1.Add("Andy");
set1.Add("Tim");
set1.Add("Steve");
set1.Add("Mark");
Console.WriteLine("Elements in HashSet1...");
foreach (string res in set1){
Console.WriteLine(res);
}
HashSet<string> set2 = new HashSet<string>();
set2.Add("Kevin");
set2.Add("Jacob");
set2.Add("Ryan");
set2.Add("Tom");
set2.Add("Andy");
set2.Add("Tim");
set2.Add("Steve");
set2.Add("Mark");
Console.WriteLine("Elements in HashSet2...");
foreach (string res in set2){
Console.WriteLine(res);
}
Console.WriteLine("Is HashSet1 equal to HashSet2? = "+set1.Equals(set2));
set2.ExceptWith(set1);
//显示set2中不在set1上的元素
foreach(string i in set2){
Console.WriteLine(i);
}
}
}输出结果
这将产生以下输出-
Elements in HashSet1... Jacob Ryan Tom Andy Tim Steve Mark Elements in HashSet2... Kevin Jacob Ryan Tom Andy Tim Steve Mark Is HashSet1 equal to HashSet2? = False Kevin
热门推荐
10 姐妹结婚红包简短祝福语
11 五一祝福语大全简短最新
12 双节祝福语简短英文
13 中秋祝福语简短版大全
14 姨父生日祝福语简短精辟
15 讲课祝福语简短10字
16 老公生日祝福语简短好看
17 新年祝福语长辈简短红包
18 新年送老师简短祝福语