บทความนี้สาธิตวิธีการดึง (get) และตั้งค่า (set) ค่าที่เกี่ยวข้องกับคีย์ที่ระบุใน SortedList โดยใช้ indexer [key]
ตัวอย่างที่ 1: ดึงและตั้งค่าผ่าน Indexer
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
SortedList list = new SortedList();
list.Add("A", "Books");
list.Add("B", "Electronics");
list.Add("C", "Appliances");
list.Add("D", "Pet Supplies");
list.Add("E", "Clothing");
list.Add("F", "Footwear");
Console.WriteLine("Value associated with key E = " + list["E"]);
list["E"] = "HDD"; // ตั้งค่าใหม่
Console.WriteLine("Value associated with key E [Updated] = " + list["E"]);
}
}
ผลลัพธ์
Value associated with key E = Clothing Value associated with key E [Updated] = HDD
ตัวอย่างที่ 2: ดึงค่าโดยไม่ตั้งค่า
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
SortedList list = new SortedList();
list.Add("A", "Books");
list.Add("B", "Electronics");
list.Add("C", "Appliances");
list.Add("D", "Pet Supplies");
list.Add("E", "Clothing");
list.Add("F", "Footwear");
Console.WriteLine("Value associated with key D = " + list["D"]);
}
}
ผลลัพธ์
Value associated with key D = Pet Supplies
คำอธิบายเพิ่มเติม
SortedList[key]ใช้ได้ทั้ง get และ set ค่า (indexer)- Get: คืนค่าที่เกี่ยวกับคีย์, คืน null ถ้าคีย์ไม่มีอยู่ (ไม่โยน exception)
- Set: ถ้าคีย์มีอยู่ -> อัปเดตค่า, ถ้าไม่มี -> เพิ่มรายการใหม่ (upsert)
- SortedList จัดเรียงตามคีย์อัตโนมัติ - indexer ใช้ binary search O(log n)
- Key และ Value เป็น object - ต้อง cast ตอนใช้งาน (non-generic)
- แนะนำใช้
SortedList<TKey, TValue>(generic) แทนสำหรับโค้ดใหม่ - มี method
ContainsKey(key)และContainsValue(value)สำหรับตรวจสอบก่อนเข้าถึง