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

วิธีสร้าง Dictionary ใน C#

Dictionary<TKey, TValue> เป็นคอลเลกชัน Key-Value อยู่ใน Namespace System.Collections.Generic

ขั้นตอนสร้างและเพิ่มข้อมูล

IDictionary<int, int> dict = new Dictionary<int, int>();
dict.Add(1, 44);
dict.Add(2, 34);
dict.Add(3, 66);
dict.Add(4, 47);
dict.Add(5, 76);

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

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        IDictionary<int, int> d = new Dictionary<int, int>();
        d.Add(1, 44);
        d.Add(2, 34);
        d.Add(3, 66);
        d.Add(4, 47);
        d.Add(5, 76);
        
        Console.WriteLine("Count: " + d.Count);
        
        // วนลูปอ่านค่า
        foreach (var kvp in d)
        {
            Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
        }
        
        // เข้าถึงโดย Key
        Console.WriteLine("Value of key 3: " + d[3]);
    }
}

ผลลัพธ์

Count: 5
Key: 1, Value: 44
Key: 2, Value: 34
Key: 3, Value: 66
Key: 4, Value: 47
Key: 5, Value: 76
Value of key 3: 66

เมธอดสำคัญ

  • Add(key, value) - เพิ่ม (โยน Exception ถ้า Key ซ้ำ)
  • TryAdd(key, value) - เพิ่ม คืน true/false (C# 9+)
  • ContainsKey(key) - ตรวจสอบ Key
  • TryGetValue(key, out value) - ดึงค่าอย่างปลอดภัย
  • Remove(key) - ลบโดย Key