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

วิธี Update ค่าใน Dictionary ใน C#

Dictionary ใน C# คืออะไร?

Generic Collection เก็บข้อมูลแบบ Key/Value Pair

  • Key: ไม่ซ้ำกัน (Unique), ไม่เป็น Null ได้
  • Value: ซ้ำได้, เป็น Null ได้

วิธี Update ค่า

ใช้ Key เป็น Indexer โดยตรง:

myDictionary[myKey] = myNewValue;
  • ถ้า Key มีอยู่แล้ว → Update ค่า
  • ถ้า Key ไม่มี → เพิ่มใหม่ (Insert)
  • ต้องการ Check ก่อน Update ใช้ ContainsKey หรือ TryGetValue

ตัวอย่างโค้ด

using System;
using System.Collections.Generic;

namespace DemoApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> students = new Dictionary<int, string>()
            {
                { 1, "John" },
                { 2, "Mrk" },    // ผิดสะกด
                { 3, "Bill" }
            };

            Console.WriteLine($"Before: ID 2 = {students[2]}"); // Mrk
            
            // Update ค่า
            students[2] = "Mark";
            
            Console.WriteLine($"After: ID 2 = {students[2]}");  // Mark
            
            // ตรวจสอบก่อน Update (Best Practice)
            if (students.ContainsKey(4))
            {
                students[4] = "New Student";
            }
            else
            {
                Console.WriteLine("ID 4 not found");
            }
            
            // TryGetValue - ปลอดภัยกว่า
            if (students.TryGetValue(2, out string name))
            {
                Console.WriteLine($"Found: {name}");
            }
            
            Console.ReadLine();
        }
    }
}

Output

Before: ID 2 = Mrk
After: ID 2 = Mark
ID 4 not found
Found: Mark

Method อื่นๆ ที่เกี่ยวข้อง

Methodคำอธิบาย
Add(key, value)เพิ่มใหม่ Throw Exception ถ้า Key ซ้ำ
TryAdd(key, value)เพิ่มใหม่ คืน false ถ้า Key ซ้ำ (ไม่ Throw)
Remove(key)ลบด้วย Key คืน bool
Clear()ลบทั้งหมด