Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

คุณสมบัติ SortedDictionary.Item[] (Indexer) ใน C# : เข้าถึงค่าด้วยคีย์

คุณสมบัติ SortedDictionary<TKey, TValue>.Item[] (Indexer) ใน C# ใช้สำหรับ ดึง (get) หรือ ตั้ง (set) ค่าที่เชื่อมโยงกับคีย์ที่ระบุ นี่คือวิธีหลักในการเข้าถึงข้อมูลใน Dictionary

รูปแบบไวยากรณ์ (Syntax)

public TValue this[TKey key] { get; set; }
  • key : คีย์ของค่าที่ต้องการดึงหรือตั้ง
  • Get : คืนค่า Value ที่เชื่อมโยงกับ Key (โยน KeyNotFoundException หากไม่มี Key)
  • Set : ตั้งค่า Value ใหม่ให้กับ Key (เพิ่มใหม่หาก Key ไม่มี, อัปเดตหาก Key มีอยู่แล้ว)

ตัวอย่างที่ 1: การใช้งาน Indexer พื้นฐาน

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedDictionary sortedDict = new SortedDictionary();
        
        sortedDict.Add(1, "One");
        sortedDict.Add(2, "Two");
        sortedDict.Add(3, "Three");
        sortedDict.Add(4, "Four");
        sortedDict.Add(5, "Five");
        sortedDict.Add(6, "Six");
        
        Console.WriteLine("SortedDictionary key-value pairs...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
        
        Console.WriteLine("Count = " + sortedDict.Count);
        
        sortedDict.Add(7, "Seven");
        sortedDict.Add(8, "Eight");
        
        Console.WriteLine("\nSortedDictionary key-value pairs...UPDATED");
        demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
        
        Console.WriteLine("Count (UPDATED) = " + sortedDict.Count);
        
        // ใช้ Indexer (Item property) ดึงค่า
        Console.WriteLine("Value at key 5 = " + sortedDict[5]); // "Five"
        
        sortedDict.Clear();
        Console.WriteLine("\nCount after Clear = " + sortedDict.Count);
    }
}

ผลลัพธ์

SortedDictionary key-value pairs...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Count = 6
SortedDictionary key-value pairs...UPDATED
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Key = 7, Value = Seven
Key = 8, Value = Eight
Count (UPDATED) = 8
Value at key 5 = Five
Count after Clear = 0

ตัวอย่างที่ 2: อัปเดตค่าผ่าน Indexer

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedDictionary sortedDict = new SortedDictionary();
        
        sortedDict.Add(1, "SUV");
        sortedDict.Add(2, "MUV");
        sortedDict.Add(3, "Utility Vehicle");
        sortedDict.Add(4, "AUV");
        sortedDict.Add(5, "Hatchback");
        sortedDict.Add(6, "Convertible");
        
        Console.WriteLine("SortedDictionary key-value pairs...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
        
        Console.WriteLine("Count = " + sortedDict.Count);
        
        sortedDict.Add(7, "Seven");
        sortedDict.Add(8, "Eight");
        
        Console.WriteLine("\nSortedDictionary key-value pairs...UPDATED");
        demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
        
        Console.WriteLine("Count (UPDATED) = " + sortedDict.Count);
        
        // ดึงค่าเก่า แล้วอัปเดตค่าใหม่
        Console.WriteLine("Value at key 5 = " + sortedDict[5]); // "Hatchback"
        sortedDict[5] = "Crossover"; // อัปเดตค่า
        Console.WriteLine("Value at key 5 (updated) = " + sortedDict[5]); // "Crossover"
        
        sortedDict.Clear();
        Console.WriteLine("\nCount after Clear = " + sortedDict.Count);
    }
}

ผลลัพธ์

SortedDictionary key-value pairs...
Key = 1, Value = SUV
Key = 2, Value = MUV
Key = 3, Value = Utility Vehicle
Key = 4, Value = AUV
Key = 5, Value = Hatchback
Key = 6, Value = Convertible
Count = 6
SortedDictionary key-value pairs...UPDATED
Key = 1, Value = SUV
Key = 2, Value = MUV
Key = 3, Value = Utility Vehicle
Key = 4, Value = AUV
Key = 5, Value = Hatchback
Key = 6, Value = Convertible
Key = 7, Value = Seven
Key = 8, Value = Eight
Count (UPDATED) = 8
Value at key 5 = Hatchback
Value at key 5 (updated) = Crossover
Count after Clear = 0

สรุปและข้อแตกต่างจากเมธอดอื่นๆ

วิธีการ พฤติกรรมเมื่อ Key ไม่มีอยู่ ใช้สำหรับ
dict[key] (Indexer/Item) Throw KeyNotFoundException (get) / เพิ่มใหม่ (set) เข้าถึงค่าปกติ เมื่อมั่นใจว่ามี key
dict.TryGetValue(key, out val) คืน false, ไม่ throw exception ตรวจสอบและดึงค่าพร้อมกัน (แนะนำ)
dict.ContainsKey(key) คืน true/false ตรวจสอบก่อนเข้าถึง
dict.GetValueOrDefault(key) คืน default(TValue) หากไม่มี key ดึงค่าพร้อม default value

แนวทางปฏิบัติที่ดี (Best Practice)

// แทนที่จะทำ
if (dict.ContainsKey(key))
    value = dict[key];

// ให้ใช้ (atomic, ประสิทธิภาพดีกว่า)
if (dict.TryGetValue(key, out var value))
{
    // ใช้ value
}

// หรือสำหรับค่า default
var value = dict.GetValueOrDefault(key, "default");