SortedDictionary<TKey, TValue> เป็นคอลเลกชันคีย์-ค่าที่จัดเก็บข้อมูลเรียงลำดับตามคีย์ (sorted by key) ใช้เมธอด ContainsKey(key) เพื่อตรวจสอบว่ามีคีย์ที่ระบุอยู่หรือไม่ คืนค่า true หรือ false
ตัวอย่างโค้ด: คีย์เป็นตัวเลข
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedDictionary sortedDict = new SortedDictionary();
sortedDict.Add(100, "Mobile");
sortedDict.Add(200, "Laptop");
sortedDict.Add(300, "Desktop");
sortedDict.Add(400, "Speakers");
sortedDict.Add(500, "Headphone");
sortedDict.Add(600, "Earphone");
Console.WriteLine("SortedDictionary key-value pairs...");
IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("\nThe SortedDictionary has the key 200? = " + sortedDict.ContainsKey(200));
}
}
ผลลัพธ์
SortedDictionary key-value pairs...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone
The SortedDictionary has the key 200? = True
ตัวอย่างเพิ่มเติม: คีย์เป็นสตริง
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedDictionary sortedDict = new SortedDictionary();
sortedDict.Add("A", "John");
sortedDict.Add("B", "Andy");
sortedDict.Add("C", "Tim");
sortedDict.Add("D", "Ryan");
sortedDict.Add("E", "Kevin");
sortedDict.Add("F", "Katie");
sortedDict.Add("G", "Brad");
Console.WriteLine("SortedDictionary key-value pairs...");
IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("\nThe SortedDictionary has the key F? = " + sortedDict.ContainsKey("F"));
}
}
ผลลัพธ์
SortedDictionary key-value pairs...
Key = A, Value = John
Key = B, Value = Andy
Key = C, Value = Tim
Key = D, Value = Ryan
Key = E, Value = Kevin
Key = F, Value = Katie
Key = G, Value = Brad
The SortedDictionary has the key F? = True
คุณสมบัติสำคัญของ SortedDictionary<TKey, TValue>
- จัดเก็บข้อมูล เรียงลำดับตามคีย์ (sorted by key) โดยอัตโนมัติ
- ใช้
Red-Black Treeด้านใน - การค้นหา/เพิ่ม/ลบ ใช้เวลา O(log n) ContainsKey(key)- ตรวจสอบคีย์ (O(log n))ContainsValue(value)- ตรวจสอบค่า (O(n) ต้องสแกนทั้งหมด)TryGetValue(key, out value)- ดึงค่าและตรวจสอบพร้อมกัน (แนะนำให้ใช้แทน ContainsKey + indexer)- คีย์ต้องไม่ซ้ำกัน (unique keys)
- ต้องการ
IComparer<TKey>สำหรับการเรียงลำดับ (default ใช้ default comparer)
เมื่อไหร่ควรใช้ SortedDictionary
- ต้องการข้อมูลเรียงลำดับตามคีย์ตลอดเวลา
- ต้องการการค้นหา/เพิ่ม/ลบ ที่เร็ว (O(log n))
- ข้อมูลมีขนาดกลางถึงใหญ่
- หากข้อมูลน้อยมาก (< 10) ใช้
SortedListเร็วกว่า (cache-friendly) - หากไม่ต้องการเรียงลำดับ ใช้
Dictionary<TKey, TValue>เร็วกว่า (O(1))