將雜湊表元素複製到 C# 中的陣列例項


以下是如何將雜湊表元素複製到陣列例項的程式碼:-

示例

 線上演示

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Hashtable hash = new Hashtable();
      hash.Add("1", "AB");
      hash.Add("2", "CD");
      hash.Add("3", "EF");
      hash.Add("4", "GH");
      hash.Add("5", "IJ");
      Console.WriteLine("Hashtable Key and Value pairs...");
      foreach(DictionaryEntry entry in hash){
         Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
      }
      Console.WriteLine("Copied to Array Instance...");
      DictionaryEntry[] dictArr = new DictionaryEntry[hash.Count];
      hash.CopyTo(dictArr, 0);
      for (int i = 0; i < dictArr.Length; i++)
         Console.WriteLine("Key = "+dictArr[i].Key + ", Value = " + dictArr[i].Value);
   }
}

輸出

此程式碼會產生以下輸出:-

Hashtable Key and Value pairs...
1 and AB
2 and CD
3 and EF
4 and GH
5 and IJ
Copied to Array Instance...
Key = 1, Value = AB
Key = 2, Value = CD
Key = 3, Value = EF
Key = 4, Value = GH
Key = 5, Value = IJ

示例

現在讓我們來看另一個示例:-

 線上演示 

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Hashtable hash = new Hashtable(5);
      hash.Add("1", "AB");
      hash.Add("2", "CD");
      Console.WriteLine("Hashtable Key and Value pairs...");
      foreach(DictionaryEntry entry in hash){
         Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
      }
      Console.WriteLine("Copied to Array Instance...");
      DictionaryEntry[] dictArr = new DictionaryEntry[5];
      hash.CopyTo(dictArr, 2);
      for (int i = 0; i < dictArr.Length; i++)
         Console.WriteLine("Key = "+dictArr[i].Key + ", Value = " + dictArr[i].Value);
   }
}

輸出

此程式碼會產生以下輸出:-

Hashtable Key and Value pairs...
1 and AB
2 and CD
Copied to Array Instance...
Key = , Value =
Key = , Value =
Key = 1, Value = AB
Key = 2, Value = CD
Key = , Value =

更新日期:10-Dec-2019

153 次瀏覽

開啟你的 職業生涯

完成課程即獲得認證

立即開始
廣告