บทความนี้สาธิตวิธีการดึง (get) และตั้งค่า (set) ค่าที่เกี่ยวข้องกับคีย์ที่ระบุใน StringDictionary โดยใช้ indexer [key]
ตัวอย่างที่ 1: ดึงค่าจากคีย์
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringDictionary strDict = new StringDictionary();
strDict.Add("A", "Books");
strDict.Add("B", "Electronics");
strDict.Add("C", "Appliances");
strDict.Add("D", "Pet Supplies");
strDict.Add("E", "Clothing");
strDict.Add("F", "Footwear");
Console.WriteLine("Value associated with key D = " + strDict["D"]);
Console.WriteLine("Value associated with key F = " + strDict["F"]);
}
}
ผลลัพธ์
Value associated with key D = Pet Supplies Value associated with key F = Footwear
ตัวอย่างที่ 2: ตั้งค่าใหม่ผ่าน Indexer
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringDictionary strDict = new StringDictionary();
strDict.Add("A", "Books");
strDict.Add("B", "Electronics");
strDict.Add("C", "Appliances");
strDict.Add("D", "Pet Supplies");
strDict.Add("E", "Clothing");
strDict.Add("F", "Footwear");
Console.WriteLine("Value associated with key D = " + strDict["D"]);
Console.WriteLine("Value associated with key F = " + strDict["F"]);
strDict["F"] = "HDD"; // ตั้งค่าใหม่
Console.WriteLine("Value associated with key F (UPDATED) = " + strDict["F"]);
}
}
ผลลัพธ์
Value associated with key D = Pet Supplies Value associated with key F = Footwear Value associated with key F (UPDATED) = HDD
คำอธิบายเพิ่มเติม
StringDictionary[key]ใช้ได้ทั้ง get และ set ค่า- Key และ Value ต้องเป็น string เท่านั้น (strongly-typed)
- Key ไม่สนใจตัวพิมพ์ใหญ่เล็ก (case-insensitive) - "D" และ "d" เหมือนกัน
- ถ้า get คีย์ที่ไม่มีอยู่ จะคืน
null(ไม่โยน exception) - ถ้า set คีย์ที่ไม่มีอยู่ จะเพิ่มรายการใหม่ (upsert behavior)
- ต่างจาก
Add(key, value)ที่โยน exception ถ้าคีย์ซ้ำ - StringDictionary เป็น legacy class - โค้ดใหม่แนะนำใช้
Dictionary<string, string>