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

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

ภาพรวม

Hashtable ใน namespace System.Collections เก็บคู่คีย์-ค่า คุณสมบัติ Values คืนค่า ICollection ที่มีค่าทั้งหมด (ไม่รวมคีย์) ตัวอย่างในต้นฉบับใช้ Keys แสดงคีย์พร้อมค่า จึงปรับแก้ให้สอดคล้องกับหัวข้อ

ตัวอย่างที่ 1: ดึงค่าทั้งหมดจาก Hashtable

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.Values;
        foreach(string val in col)
            Console.WriteLine(val);
    }
}

ผลลัพธ์

Clothing
Electronics
Appliances
Pet Supplies
Books
Toys
Footwear

ตัวอย่างที่ 2: ดึงค่าพร้อมคีย์ (ใช้ Keys แทน)

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

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

  • Hashtable.Values คืนค่า ICollection ของค่าทั้งหมด ลำดับไม่ได้รับประกัน
  • Hashtable.Keys คืนค่า ICollection ของคีย์ทั้งหมด
  • Hashtable ไม่รักษาลำดับการเพิ่ม ใช้ OrderedDictionary หรือ SortedList หากต้องการลำดับ
  • Hashtable เป็น non-generic สำหรับโค้ดใหม่แนะนำ Dictionary<TKey, TValue>