在 C# 中從另一個集合建立一個雜湊集


要從另一個集合建立雜湊集,程式碼如下所示−

示例

 即時演示

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      HashSet<int> set1 = new HashSet<int>();
      set1.Add(100);
      set1.Add(200);
      set1.Add(300);
      Console.WriteLine("HashSet created from another collection...");
      foreach(int i in set1){
         Console.WriteLine(i);
      }
      HashSet<int> set2 = new HashSet<int>(set1);
      Console.WriteLine("HashSet created from another collection...");
      foreach(int i in set2){
         Console.WriteLine(i);
      }
   }
}

輸出

這將產生以下輸出 −

HashSet created from another collection...
100
200
300
HashSet created from another collection...
100
200
300

示例

現在我們來看另一個示例 −

 即時演示

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      HashSet<string> set1 = new HashSet<string>();
      set1.Add("Jacob");
      set1.Add("Tom");
      set1.Add("Harry");
      set1.Add("Harry");
      set1.Add("Tom");
      set1.Add("Harry");
      Console.WriteLine("HashSet created from another collection...");
      foreach(string i in set1){
         Console.WriteLine(i);
      }
      HashSet<string> set2 = new HashSet<string>(set1);
      Console.WriteLine("HashSet created from another collection...");
      foreach(string i in set2){
         Console.WriteLine(i);
      }
   }
}

輸出

這將產生以下輸出 −

HashSet created from another collection...
Jacob
Tom
Harry
HashSet created from another collection...
Jacob
Tom
Harry

更新日期: 05-Dec-2019

122 Views

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.