Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách khai báo và khởi tạo Dictionary trong C#

Dictionary<TKey, TValue> là tập hợp cặp khóa-giá trị kiểu mạnh, trong namespace System.Collections.Generic.

Khai báo và khởi tạo:

IDictionary<int, string> d = new Dictionary<int, string>();
// hoặc
var d = new Dictionary<int, string>();
// hoặc collection initializer
var d = new Dictionary<int, string> 
{ 
    {1, "One"}, {2, "Two"} 
};

Ví dụ

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);
    }
}

Kết quả

Dictionary elements: 4

Đặc điểm: Khóa (Key) phải duy nhất, không null (trừ nullable reference type C# 8+). Tra cứu O(1) trung bình nhờ hash table. Dùng TryGetValue để tránh exception khi key không tồn tại.