Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การคัดลอกข้อมูล Hashtable ไปยังอาร์เรย์ใน C#

ภาพรวม

Hashtable.CopyTo(Array array, int index) คัดลอกคู่คีย์/ค่าเป็น DictionaryEntry ไปยังอาร์เรย์ปลายทาง ตั้งแต่ดัชนีที่ระบุ

ตัวอย่างที่ 1: คัดลอกไปอาร์เรย์ขนาดเท่าจำนวนข้อมูล เริ่มดัชนี 0

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

ตัวอย่างที่ 2: คัดลอกไปอาร์เรย์ขนาด 5 เริ่มดัชนี 2

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 = 

สรุป

  • ใช้ DictionaryEntry[] เป็นอาร์เรย์ปลายทาง
  • ขนาดอาร์เรย์ต้อง >= จำนวนข้อมูล + ดัชนีเริ่มต้น
  • ลำดับข้อมูลใน Hashtable ไม่ได้รับประกัน (ขึ้นอยู่กับ hash code)