Lớp StringDictionary triển khai bảng băm với khóa và giá trị đều là chuỗi (thay vì object).
Thuộc tính
| STT | Thuộc tính & Mô tả |
| 1 | Count: Số cặp khóa/giá trị. |
| 2 | IsSynchronized: Cho biết có đồng bộ không. |
| 3 | Item[String]: Lấy/đặt giá trị theo khóa. |
| 4 | Keys: Tập hợp các khóa. |
| 5 | SyncRoot: Đối tượng đồng bộ hóa. |
| 6 | Values: Tập hợp các giá trị. |
Phương thức
| STT | Phương thức & Mô tả |
| 1 | Add(String, String): Thêm cặp khóa/giá trị. |
| 2 | Clear(): Xóa tất cả mục. |
| 3 | ContainsKey(String): Kiểm tra khóa tồn tại. |
| 4 | ContainsValue(String): Kiểm tra giá trị tồn tại. |
| 5 | CopyTo(Array, Int32): Sao chép vào mảng. |
Ví dụ 1: So sánh hai StringDictionary
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringDictionary strDict1 = new StringDictionary();
strDict1.Add("A", "John");
strDict1.Add("B", "Andy");
strDict1.Add("C", "Tim");
strDict1.Add("D", "Ryan");
strDict1.Add("E", "Kevin");
strDict1.Add("F", "Katie");
strDict1.Add("G", "Brad");
StringDictionary strDict2 = new StringDictionary();
strDict2.Add("A", "John");
strDict2.Add("B", "Andy");
strDict2.Add("C", "Tim");
strDict2.Add("D", "Ryan");
strDict2.Add("E", "Kevin");
strDict2.Add("F", "Katie");
strDict2.Add("G", "Brad");
StringDictionary strDict3 = new StringDictionary();
strDict3 = strDict2;
Console.WriteLine("Dictionary2 bằng Dictionary3? = " + strDict2.Equals(strDict3));
Console.WriteLine("Dictionary1 bằng Dictionary3? = " + strDict1.Equals(strDict3));
}
}
Kết quả
Dictionary2 bằng Dictionary3? = True
Dictionary1 bằng Dictionary3? = False
Ví dụ 2: Kiểm tra đồng bộ
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringDictionary strDict1 = new StringDictionary();
strDict1.Add("A", "John");
strDict1.Add("B", "Andy");
strDict1.Add("C", "Tim");
strDict1.Add("D", "Ryan");
strDict1.Add("E", "Kevin");
strDict1.Add("F", "Katie");
strDict1.Add("G", "Brad");
Console.WriteLine("Các phần tử StringDictionary1...");
foreach(DictionaryEntry de in strDict1) {
Console.WriteLine(de.Key + " " + de.Value);
}
StringDictionary strDict2 = new StringDictionary();
strDict2.Add("1", "A");
strDict2.Add("2", "B");
strDict2.Add("3", "C");
strDict2.Add("4", "D");
strDict2.Add("5", "E");
Console.WriteLine("\nCác cặp khóa-giá trị StringDictionary2...");
IEnumerator demoEnum = strDict2.GetEnumerator();
DictionaryEntry d;
while (demoEnum.MoveNext()) {
d = (DictionaryEntry)demoEnum.Current;
Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
}
Console.WriteLine("StringDictionary2 có đồng bộ? = " + strDict2.IsSynchronized);
}
}
Kết quả
Các phần tử StringDictionary1...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad
Các cặp khóa-giá trị StringDictionary2...
Key = 1, Value = A
Key = 2, Value = B
Key = 3, Value = C
Key = 4, Value = D
Key = 5, Value = E
StringDictionary2 có đồng bộ? = False