Giới thiệu
OrderedDictionary (namespace System.Collections.Specialized) lưu trữ cặp khóa-giá trị theo thứ tự thêm vào. Thuộc tính Keys trả về ICollection chứa các khóa theo thứ chèn.
Ví dụ 1: Lấy và hiển thị khóa
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
OrderedDictionary dict = new OrderedDictionary();
dict.Add("1", "One");
dict.Add("2", "Two");
dict.Add("3", "Three");
dict.Add("4", "Four");
dict.Add("5", "Five");
dict.Add("6", "Six");
dict.Add("7", "Seven");
dict.Add("8", "Eight");
ICollection col = dict.Keys;
String[] strKeys = new String[dict.Count];
col.CopyTo(strKeys, 0);
Console.WriteLine("Displaying the keys...");
for (int i = 0; i < dict.Count; i++)
{
Console.WriteLine(strKeys[i]);
}
}
}
Kết quả
Displaying the keys... 1 2 3 4 5 6 7 8
Ví dụ 2: Khóa dạng chuỗi mô tả
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
OrderedDictionary dict = new OrderedDictionary();
dict.Add("One", "John");
dict.Add("Two", "Tim");
dict.Add("Three", "Katie");
dict.Add("Four", "Andy");
dict.Add("Five", "Gary");
dict.Add("Six", "Amy");
ICollection col = dict.Keys;
String[] strKeys = new String[dict.Count];
col.CopyTo(strKeys, 0);
Console.WriteLine("Displaying the keys...");
for (int i = 0; i < dict.Count; i++)
{
Console.WriteLine(strKeys[i]);
}
}
}
Kết quả
Displaying the keys... One Two Three Four Five Six
Đặc điểm OrderedDictionary
- Giữ thứ tự chèn (insertion order)
- Truy cập bằng khóa: O(1) như Hashtable
- Truy cập bằng chỉ mục:
dict[index]hoặcdict.GetKey(index) - Khóa không được null, không trùng lặp
- Không generic - cân nhắc
OrderedDictionary<TKey, TValue>từ thư viện thứ 3 hoặc tự triển khai
Các cách duyệt OrderedDictionary
// 1. Duyệt Keys
foreach (var key in dict.Keys)
{
Console.WriteLine(key);
}
// 2. Duyệt Values
foreach (var value in dict.Values)
{
Console.WriteLine(value);
}
// 3. Duyệt DictionaryEntry (khóa + giá trị)
foreach (DictionaryEntry entry in dict)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
// 4. Duyệt bằng chỉ mục
for (int i = 0; i < dict.Count; i++)
{
Console.WriteLine($"{dict.GetKey(i)}: {dict[i]}");
}