Để lấy tập hợp các khóa (keys) từ HybridDictionary dưới dạng ICollection, bạn sử dụng thuộc tính Keys. Sau đó có thể sao chép vào mảng hoặc duyệt trực tiếp.
Ví dụ 1: Sao chép khóa vào mảng string
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
HybridDictionary dict = new HybridDictionary();
dict.Add("One", "Katie");
dict.Add("Two", "Andy");
dict.Add("Three", "Gary");
dict.Add("Four", "Mark");
dict.Add("Five", "Marie");
dict.Add("Six", "Sam");
dict.Add("Seven", "Harry");
dict.Add("Eight", "Kevin");
dict.Add("Nine", "Ryan");
// Tạo mảng string với kích thước bằng số phần tử
String[] strArr = new String[dict.Count];
// Sao chép keys vào mảng bắt đầu từ chỉ mục 0
dict.Keys.CopyTo(strArr, 0);
Console.WriteLine("Các khóa trong HybridDictionary:");
for (int i = 0; i < dict.Count; i++)
{
Console.WriteLine(strArr[i]);
}
}
}
Kết quả
Eight Seven Four Three One Five Six Two Nine
Ví dụ 2: Duyệt trực tiếp qua Keys
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
HybridDictionary dict = new HybridDictionary();
dict.Add("1", "A");
dict.Add("2", "B");
dict.Add("3", "C");
dict.Add("4", "D");
dict.Add("5", "E");
dict.Add("6", "F");
Console.WriteLine("Các khóa (duyệt trực tiếp):");
foreach (var key in dict.Keys)
{
Console.WriteLine(key);
}
Console.WriteLine("\nCác cặp Key-Value:");
foreach (DictionaryEntry entry in dict)
{
Console.WriteLine($"Key = {entry.Key}, Value = {entry.Value}");
}
}
}
Kết quả
Các khóa (duyệt trực tiếp): 1 2 3 4 5 6 Các cặp Key-Value: Key = 1, Value = A Key = 2, Value = B Key = 3, Value = C Key = 4, Value = D Key = 5, Value = E Key = 6, Value = F
Lưu ý quan trọng
HybridDictionary.Keystrả vềICollection- chỉ đọc, không thể thêm/xóa khóa trực tiếp- Thứ tự các khóa không được bảo đảm (tùy thuộc implementation nội bộ)
- Sử dụng
CopyTo()để sao chép vào mảng nếu cần thao tác thêm - HybridDictionary không giữ thứ tự thêm vào - dùng
OrderedDictionarynếu cần giữ thứ tự
So sánh với Dictionary<TKey, TValue>
// Dictionary<TKey, TValue> (khuyến nghị cho code mới)
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "Katie");
// Lấy keys
var keys = dict.Keys; // Trả về Dictionary<TKey, TValue>.KeyCollection
foreach (var key in keys) { ... }
// Hoặc chuyển thành List
var keyList = dict.Keys.ToList();