Để xóa tất cả các phần tử trong một tập hợp khỏi HashSet, mã như sau -
Ví dụ
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);
// displaying elements in set2, which are not on set1
foreach(string i in set2){
Console.WriteLine(i);
}
}
} Đầu ra
Điều này sẽ tạo ra kết quả sau -
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
Ví dụ
Hãy để chúng tôi xem một ví dụ khác -
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);
// displaying elements in set2, which are not on set1
foreach(string i in set2){
Console.WriteLine(i);
}
}
} Đầu ra
Điều này sẽ tạo ra kết quả sau -
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