ใน C# พจนานุกรมคือคอลเล็กชันทั่วไปซึ่งโดยทั่วไปจะใช้เพื่อจัดเก็บคู่คีย์/ค่า ในพจนานุกรม คีย์ไม่สามารถเป็นค่าว่างได้ แต่ค่าสามารถเป็นได้ คีย์ต้องไม่ซ้ำกัน ไม่อนุญาตให้ใช้คีย์ซ้ำ หากเราพยายามใช้คีย์ที่ซ้ำกัน คอมไพเลอร์จะส่งข้อยกเว้น
ตามที่กล่าวไว้ข้างต้น ค่าในพจนานุกรมสามารถอัปเดตได้โดยใช้คีย์ เนื่องจากคีย์จะไม่ซ้ำกันสำหรับทุกค่า
myDictionary[myKey] = myNewValue;
ตัวอย่าง
มาดูพจนานุกรมของนักเรียนที่มีรหัสและชื่อกัน ตอนนี้ถ้าเราต้องการเปลี่ยนชื่อนักเรียนที่มี id 2 จาก "Mrk" เป็น "Mark"
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($"Name of student having id 2: {students[2]}");
students[2] = "Mark";
Console.WriteLine($"Updated Name of student having id 2: {students[2]}");
Console.ReadLine();
}
}
} ผลลัพธ์
ผลลัพธ์ของโค้ดด้านบนคือ −
Name of student having id 2: Mrk Updated Name of student having id 2: Mark