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

Values Property ของ Hashtable Class ใน C#

Hashtable เป็นคอลเลกชัน Key-Value Pair แบบ Non-generic (เก็บเป็น object) Property Values คืนค่า ICollection ที่มี Values ทั้งหมดใน Hashtable ไม่มีการรับประกันลำดับ (Unordered)

การประกาศและเพิ่มข้อมูล

using System.Collections;

Hashtable ht = new Hashtable();
ht.Add("One", "Henry");
ht.Add("Two", "Kevin");
ht.Add("Three", "David");

ใช้งาน Values Property

using System;
using System.Collections;

namespace Demo {
    class Program {
        static void Main(string[] args) {
            Hashtable ht = new Hashtable();
            ht.Add("One", "Henry");
            ht.Add("Two", "Kevin");
            ht.Add("Three", "David");
            
            // Values Property - คืน ICollection (Unordered)
            foreach (string value in ht.Values) {
                Console.WriteLine(value);
            }
            
            Console.ReadKey();
        }
    }
}

ผลลัพธ์ (ลำดับอาจแตกต่างไป)

David
Henry
Kevin

⚠️ **หมายเหตุ**: Hashtable ไม่รับประกันลำดับ ผลลัพธ์อาจเป็น Henry, Kevin, David หรือลำดับอื่นก็ได้

Properties และ Methods สำคัญของ Hashtable

Member คำอธิบาย
Keys ICollection ของ Keys (Unordered)
Values ICollection ของ Values (Unordered)
Count จำนวน Key-Value Pairs
IsFixedSize มีขนาดคงที่หรือไม่
IsReadOnly Read-only หรือไม่
Item[key] Indexer - Get/Set ค่าด้วย Key
Add(key, value) เพิ่ม Key-Value Pair
Remove(key) ลบด้วย Key
ContainsKey(key) ตรวจสอบ Key (เร็วกว่า Contains)
ContainsValue(value) ตรวจสอบ Value (ช้า O(n))
Clear() ล้างทั้งหมด
Clone() Shallow Copy

Iterate Keys และ Values พร้อมกัน

// 1. ใช้ Keys แล้ว Indexer
foreach (var key in ht.Keys) {
    Console.WriteLine($"{key}: {ht[key]}");
}

// 2. ใช้ DictionaryEntry (ใน foreach ของ Hashtable)
foreach (DictionaryEntry entry in ht) {
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

// 3. Cast เป็น DictionaryEntry[]
var entries = new DictionaryEntry[ht.Count];
ht.CopyTo(entries, 0);

Hashtable vs Dictionary<TKey, TValue> (แนะนำใช้ Dictionary)

Feature Hashtable Dictionary<TKey, TValue>
Type Safety ❌ Object-based (Boxing/Unboxing) ✅ Generic (Type-safe)
Performance ช้ากว่า (Boxing) เร็วกว่า
Null Key ✅ อนุญาต (หนึ่งค่า) ❌ ไม่อนุญาต (Throw Exception)
Thread Safety ✅ สำหรับ Reader (Single Writer) ❌ ไม่ Thread-safe
Order Unordered Unordered (แต่ Preserves Insertion Order ใน .NET Core 3.0+)

Generic Equivalent: Dictionary<TKey, TValue>

using System.Collections.Generic;

var dict = new Dictionary {
    { "One", "Henry" },
    { "Two", "Kevin" },
    { "Three", "David" }
};

// Values Property - Type-safe
foreach (string value in dict.Values) {
    Console.WriteLine(value);
}

// Keys
foreach (string key in dict.Keys) {
    Console.WriteLine(key);
}

// KeyValuePair Iteration
foreach (var kvp in dict) {
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

Thread-Safe Alternative

using System.Collections.Concurrent;

// Thread-safe Dictionary
var concurrentDict = new ConcurrentDictionary();
concurrentDict.TryAdd("One", "Henry");

// Thread-safe Hashtable Alternative (Legacy)
var syncHashtable = Hashtable.Synchronized(new Hashtable());

Best Practices

  • ใช้ Dictionary<TKey, TValue> แทน Hashtable ในโค้ดใหม่ (Type-safe, Faster)
  • Hashtable ใช้ได้เฉพาะ Legacy Code หรือ Interop กับ COM/Non-generic APIs
  • Values Property คืน ICollection View - ไม่ Copy ข้อมูล (O(1))
  • ไม่ควรพึ่งพาลำดับของ Values/Keys ใน Hashtable