Dictionary ใน C# เป็นคอลเลกชันของคีย์และค่า (Key-Value Pairs) เป็นคลาสเจเนริกในเนมสเปซ System.Collections.Generic
ไวยากรณ์
public class Dictionary<TKey, TValue>
TKey คือประเภทของคีย์ ส่วน TValue คือประเภทของค่า
ตัวอย่างที่ 1: สร้าง Dictionary และเพิ่มข้อมูล
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: ลบคีย์ออกจาก Dictionary
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "Kagido");
dict.Add("Two", "Ngidi");
dict.Add("Three", "Devillers");
dict.Add("Four", "Smith");
dict.Add("Five", "Warner");
Console.WriteLine("Count of elements = " + dict.Count);
Console.WriteLine("Removing some keys...");
dict.Remove("Four");
dict.Remove("Five");
Console.WriteLine("Count of elements (updated) = " + dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach (KeyValuePair<string, string> res in dict)
{
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.Write("\nAll the keys..\n");
Dictionary<string, string>.KeyCollection allKeys = dict.Keys;
foreach (string str in allKeys)
{
Console.WriteLine("Key = {0}", str);
}
}
}
ผลลัพธ์
Count of elements = 5
Removing some keys...
Count of elements (updated) = 3
Key/value pairs...
Key = One, Value = Kagido
Key = Two, Value = Ngidi
Key = Three, Value = Devillers
All the keys..
Key = One
Key = Two
Key = Three
คุณสมบัติสำคัญ: Dictionary ไม่อนุญาตให้มีคีย์ซ้ำ คีย์ต้องเป็นค่าเฉพาะ (Unique) และไม่สามารถเป็น null ได้ (สำหรับ reference type)