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

ดึง ICollection ที่มีคีย์ใน Hashtable ใน C#

ภาพรวม

คุณสมบัติ Hashtable.Keys คืนค่า ICollection ที่มีคีย์ทั้งหมดใน Hashtable สามารถใช้วนลูปหรือคัดลอกไปยังอาร์เรย์ได้

ตัวอย่างที่ 1: ดึงคีย์และแสดงค่าที่สอดคล้อง

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable hash = new Hashtable();
        hash.Add("A", "Electronics");
        hash.Add("B", "Appliances");
        hash.Add("C", "Pet Supplies");
        hash.Add("D", "Books");
        hash.Add("E", "Toys");
        hash.Add("F", "Footwear");
        hash.Add("G", "Clothing");
        ICollection col = hash.Keys;
        foreach(string key in col)
            Console.WriteLine(key + ": " + hash[key]);
    }
}

ผลลัพธ์

G: Clothing
A: Electronics
B: Appliances
C: Pet Supplies
D: Books
E: Toys
F: Footwear

ตัวอย่างที่ 2: ดึงคีย์แบบตัวเลข

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");
        hash.Add(6, "KL");
        hash.Add(7, "MN");
        ICollection col = hash.Keys;
        foreach(int key in col)
            Console.WriteLine("Key = " + key + ", Value = " + hash[key]);
    }
}

ผลลัพธ์

Key = 7, Value = MN
Key = 6, Value = KL
Key = 5, Value = IJ
Key = 4, Value = GH
Key = 3, Value = EF
Key = 2, Value = CD
Key = 1, Value = AB

คำอธิบายเพิ่มเติม

  • Keys คืนค่า ICollection ที่เป็น snapshot ของคีย์ ณ ขณะนั้น
  • ลำดับคีย์ไม่ได้รับประกัน (ขึ้นอยู่กับ hash code และการจัดเก็บภายใน)
  • สามารถใช้ CopyTo() คัดลอกคีย์ไปยังอาร์เรย์ได้
  • สำหรับการค้นหาคีย์เฉพาะ ใช้ ContainsKey() ซึ่งเร็วกว่าการวนลูป (O(1) เฉลี่ย)