Giới thiệu
StringDictionary (namespace System.Collections.Specialized) là từ điển chỉ chấp nhận khóa và giá trị kiểu string. Khóa tự động chuyển thành chữ thường (case-insensitive key).
Ví dụ 1: Thêm 7 cặp khóa-giá trị
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringDictionary strDict = new StringDictionary();
strDict.Add("A", "John");
strDict.Add("B", "Andy");
strDict.Add("C", "Tim");
strDict.Add("D", "Ryan");
strDict.Add("E", "Kevin");
strDict.Add("F", "Katie");
strDict.Add("G", "Brad");
Console.WriteLine("Các phần tử StringDictionary...");
foreach (DictionaryEntry de in strDict)
{
Console.WriteLine(de.Key + " " + de.Value);
}
}
}
Kết quả
Các phần tử StringDictionary...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad
Ví dụ 2: Thêm 3 cặp
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringDictionary strDict = new StringDictionary();
strDict.Add("1", "Electric Cars");
strDict.Add("2", "SUV");
strDict.Add("3", "AUV");
Console.WriteLine("Các phần tử StringDictionary...");
foreach (DictionaryEntry de in strDict)
{
Console.WriteLine(de.Key + " " + de.Value);
}
}
}
Kết quả
Các phần tử StringDictionary...
1 Electric Cars
2 SUV
3 AUV
Đặc điểm quan trọng
- Khóa không phân biệt chữ hoa/thường:
Add("A", "x")vàAdd("a", "y")sẽ ghi đè. - Chỉ chứa string; null không được phép cho khóa.
- Triển khai dùng
Hashtablenội bộ. - Trong code mới, nên dùng
Dictionary<string, string>hoặcConcurrentDictionary<string, string>.