บทนำ
เมธอด Dictionary.Add() ใน C# ใช้เพิ่มคีย์และค่าที่ระบุเข้าไปใน Dictionary หากคีย์มีอยู่แล้ว จะโยนข้อยกเว้น ArgumentException
ไวยากรณ์ (Syntax)
public void Add (TKey key, TValue val);
โดยที่ key คือคีย์ และ val คือค่าขององค์ประกอบ
ตัวอย่างที่ 1: เพิ่มข้อมูลพื้นฐาน
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("Key/value pairs...");
foreach (KeyValuePair<string, string> res in dict)
{
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
}
}
ผลลัพธ์
Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan
ตัวอย่างที่ 2: เพิ่มข้อมูลและตรวจสอบจำนวนสมาชิก
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = " + dict.Count);
dict.Add("Six", "Anne");
dict.Add("Seven", "Katie");
Console.WriteLine("Count of elements (updated) = " + dict.Count);
Console.WriteLine("Key/value pairs...");
foreach (KeyValuePair<string, string> res in dict)
{
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
}
}
ผลลัพธ์
Count of elements = 5 Count of elements (updated) = 7 Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan Key = Six, Value = Anne Key = Seven, Value = Katie
สรุป
เมธอด Add() ต้องการคีย์ที่ไม่ซ้ำกัน (unique) หากต้องการเพิ่มหรืออัปเดตโดยไม่กังวลข้อยกเว้น ให้ใช้ indexer dict[key] = value หรือเมธอด TryAdd() (ใน .NET Core 2.0+) ซึ่งคืน bool แทนการโยนข้อยกเว้น