ภาพรวม
OrderedDictionary ใน System.Collections.Specialized เก็บคู่คีย์/ค่า รักษาลำดับการเพิ่ม (insertion order) เข้าถึงได้ทั้งคีย์และดัชนี
ตัวอย่างที่ 1: สร้าง เพิ่มข้อมูล ลบ และนับจำนวน
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
OrderedDictionary dict = new OrderedDictionary();
dict.Add("A", "Books");
dict.Add("B", "Electronics");
dict.Add("C", "Smart Wearables");
dict.Add("D", "Pet Supplies");
dict.Add("E", "Clothing");
dict.Add("F", "Footwear");
Console.WriteLine("OrderedDictionary elements...");
foreach (DictionaryEntry d in dict)
{
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);
dict.Remove("E");
Console.WriteLine("Count of elements in OrderedDictionary (Updated) = " + dict.Count);
}
}
ผลลัพธ์
OrderedDictionary elements... A Books B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear Count of elements in OrderedDictionary = 6 Count of elements in OrderedDictionary (Updated) = 5
ตัวอย่างที่ 2: สร้าง 8 คู่ และดึงคีย์ทั้งหมดไปอาร์เรย์
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]);
}
}
}
ผลลัพธ์
Displaying the keys... 1 2 3 4 5 6 7 8
สรุป
- รักษาลำดับการเพิ่ม (insertion order) ต่างจาก Hashtable/SortedList
- เข้าถึงได้ด้วยคีย์
dict[key]หรือดัชนีdict[index] - มี
Keys,Valuesคืน ICollection - เหมาะเมื่อต้องการลำดับคงที่และเข้าถึงด้วยคีย์/ดัชนี