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

เมธอด SortedDictionary.Add() ใน C# : เพิ่มคู่ Key-Value ใหม่

เมธอด SortedDictionary<TKey, TValue>.Add() ใน C# ใช้เพิ่มคู่คีย์-ค่า (key-value pair) ใหม่เข้าไปใน SortedDictionary คีย์จะถูกจัดเรียงอัตโนมัติตามลำดับ (ascending order)

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

public void Add(TKey key, TValue value);
  • key : คีย์ของสมาชิก (ต้อง unique, ไม่เป็น null สำหรับ reference types)
  • value : ค่าที่เชื่อมโยงกับคีย์ (สามารถเป็น null ได้สำหรับ reference types)

ข้อยกเว้น (Exceptions)

  • ArgumentNullException : key เป็น null
  • ArgumentException : key มีอยู่ใน Dictionary แล้ว (duplicate key)

ตัวอย่างที่ 1: เพิ่มข้อมูล int key, string value

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... (sorted by key)");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
    }
}

ผลลัพธ์

SortedDictionary key-value pairs... (sorted by key)
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone

ตัวอย่างที่ 2: String Key และ ContainsKey

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... (sorted by string key)");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
        
        Console.WriteLine("\nContains Key 'F'? = " + sortedDict.ContainsKey("F"));
    }
}

ผลลัพธ์

SortedDictionary key-value pairs... (sorted by string key)
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
Contains Key 'F'? = True

สรุปและแนวทางปฏิบัติ

  • Key ต้อง Unique - เพิ่ม Key ซ้ำจะโยน ArgumentException
  • ใช้ TryAdd() (.NET Core 2.0+/ .NET 5+) เพื่อเพิ่มโดยไม่โยน exception:
// .NET Core 2.0+ / .NET 5+
if (sortedDict.TryAdd(key, value))
{
    // เพิ่มสำเร็จ
}
else
{
    // Key มีอยู่แล้ว
}
  • หรือใช้ Indexer dict[key] = value ซึ่งจะเพิ่มใหม่หรืออัปเดตได้ (ไม่โยน exception)
  • SortedDictionary ใช้ Red-Back Tree ภายใน - Add/Remove/Search = O(log n)
  • เหมาะสำหรับ: ต้องการข้อมูลเรียงตาม Key เสมอ, Range queries, Ordered enumeration
  • ไม่เหมาะสำหรับ: Lookup บ่อยมาก (ใช้ Dictionary<TKey,TValue> O(1) เร็วกว่า)

ตัวอย่างการจัดการ Duplicate Key อย่างปลอดภัย

// Pattern แนะนำ
if (!sortedDict.ContainsKey(key))
{
    sortedDict.Add(key, value);
}
// หรือ
sortedDict[key] = value; // Upsert (insert or update)