檢查兩個 HashSet 物件是否相等(C#)


要檢查兩個 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("Elements in HashSet2...");
      foreach (string res in set2) {
         Console.WriteLine(res);
      }
      HashSet<string> set3 = new HashSet<string>();
      set3 = set2;
      Console.WriteLine("Is HashSet3 equal to HashSet2? = "+set3.Equals(set2));
   }
}

輸出

這將產生以下輸出 -

Elements in HashSet1...
A
B
C
D
E
F
G
H
Elements in HashSet2...
John
Jacob
Ryan
Tom
Andy
Tim
Steve
Mark
Is HashSet3 equal to HashSet2? = True

示例

我們再來看一個示例 -

 線上演示

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("Elements in HashSet2...");
      foreach (string res in set2){
         Console.WriteLine(res);
      }
      Console.WriteLine("Is HashSet2 equal to HashSet1? = "+set2.Equals(set1));
   }
}

輸出

這將產生以下輸出 -

Elements in HashSet1...
A
B
C
D
E
F
G
H
Elements in HashSet2...
John
Jacob
Ryan
Tom
Andy
Tim
Steve
Mark
Is HashSet2 equal to HashSet1? = False

更新於: 05-12-2019

278 瀏覽次數

開啟你的 職業 生涯

透過完成本課程獲得認證

開始吧
廣告