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

วิธีการประกาศและกำหนดค่าเริ่มต้น Dictionary ใน C#

Dictionary เป็นคอลเลกชันของคีย์และค่าใน C# อยู่ในเนมสเปซ System.Collections.Generic

การประกาศและ Initialize

IDictionary<int, string> d = new Dictionary<int, string>();

ชนิดของคีย์และค่าจะระบุขณะประกาศ ตัวอย่าง Key เป็น int, Value เป็น string

ตัวอย่าง

using System;
using System.Collections.Generic;

public class Demo {
    public static void Main() {
        IDictionary<int, int> d = new Dictionary<int, int>();
        d.Add(1, 97);
        d.Add(2, 89);
        d.Add(3, 77);
        d.Add(4, 88);
        Console.WriteLine("Dictionary elements: " + d.Count);
    }
}

ผลลัพธ์

Dictionary elements: 4