Giới thiệu
StringDictionary cho phép truy xuất và gán giá trị thông qua chỉ số (indexer) với khóa là chuỗi. Cú pháp: dict[key] để lấy giá trị, dict[key] = value để đặt giá trị mới. Nếu khóa không tồn tại khi lấy, trả về null; khi đặt, sẽ thêm mới cặp khóa/giá trị.
Ví dụ 1: Chỉ lấy giá trị
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringDictionary strDict = new StringDictionary();
strDict.Add("A", "Books");
strDict.Add("B", "Electronics");
strDict.Add("C", "Appliances");
strDict.Add("D", "Pet Supplies");
strDict.Add("E", "Clothing");
strDict.Add("F", "Footwear");
Console.WriteLine("Giá trị liên kết với khóa D = " + strDict["D"]);
Console.WriteLine("Giá trị liên kết với khóa F = " + strDict["F"]);
}
}
Kết quả
Giá trị liên kết với khóa D = Pet Supplies Giá trị liên kết với khóa F = Footwear
Ví dụ 2: Lấy và cập nhật giá trị
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringDictionary strDict = new StringDictionary();
strDict.Add("A", "Books");
strDict.Add("B", "Electronics");
strDict.Add("C", "Appliances");
strDict.Add("D", "Pet Supplies");
strDict.Add("E", "Clothing");
strDict.Add("F", "Footwear");
Console.WriteLine("Giá trị liên kết với khóa D = " + strDict["D"]);
Console.WriteLine("Giá trị liên kết với khóa F = " + strDict["F"]);
strDict["F"] = "HDD"; // Cập nhật giá trị cho khóa F
Console.WriteLine("Giá trị liên kết với khóa F (ĐÃ CẬP NHẬT) = " + strDict["F"]);
}
}
Kết quả
Giá trị liên kết với khóa D = Pet Supplies Giá trị liên kết với khóa F = Footwear Giá trị liên kết với khóa F (ĐÃ CẬP NHẬT) = HDD
Lưu ý: Khóa trong StringDictionary không phân biệt chữ hoa/thường (case-insensitive). Giá trị phải là chuỗi. Nếu gán giá trị cho khóa chưa tồn tại, cặp mới sẽ được thêm vào.