Giới thiệu
Thuộc tính Keys của Hashtable trả về một ICollection chứa tất cả các khóa. Điều này hữu ích khi cần duyệt qua khóa hoặc sao chép khóa vào mảng.
Ví dụ 1: Lấy và hiển thị tất cả khóa
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 str in col)
{
Console.WriteLine(str + ": " + hash[str]);
}
}
}
Kết quả
G: Clothing A: Electronics B: Appliances C: Pet Supplies D: Books E: Toys F: Footwear
Ví dụ 2: Khóa kiểu số nguyên
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 str in col)
{
Console.WriteLine("Key = " + str + ", Value = " + hash[str]);
}
}
}
Kết quả
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
Các cách duyệt Hashtable hiệu quả hơn
// Cách 1: Duyệt DictionaryEntry (khuyên dùng)
foreach (DictionaryEntry entry in hash)
{
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}
// Cách 2: Duyệt Keys rồi lấy giá trị (chậm hơn)
foreach (var key in hash.Keys)
{
Console.WriteLine($"Key: {key}, Value: {hash[key]}");
}
// Cách 3: Sao chép khóa vào mảng
string[] keys = new string[hash.Count];
hash.Keys.CopyTo(keys, 0);
Khuyến nghị
Trong code hiện đại, hãy sử dụng Dictionary<TKey, TValue> thay vì Hashtable để có kiểu mạnh, hiệu suất tốt hơn và tránh boxing/unboxing.