Giới thiệu
HybridDictionary cho phép tạo phiên bản phân biệt chữ hoa/thường (case-sensitive) bằng constructor new HybridDictionary(false). Mặc định là case-insensitive (true).
Ví dụ 1: HybridDictionary case-sensitive (false)
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
HybridDictionary dict = new HybridDictionary(false); // Case-sensitive
dict.Add("A", "AB");
dict.Add("B", "BC");
dict.Add("C", "DE");
dict.Add("D", "de"); // 'D' và 'd' khác nhau
Console.WriteLine("Key/Value pairs...");
foreach (DictionaryEntry de in dict)
{
Console.WriteLine("Key = " + de.Key + ", Value = " + de.Value);
}
}
}
Kết quả
Key/Value pairs... Key = A, Value = AB Key = B, Value = BC Key = C, Value = DE Key = D, Value = de
Ví dụ 2: HybridDictionary case-insensitive (true)
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
HybridDictionary dict = new HybridDictionary(true); // Case-insensitive (mặc định)
dict.Add("A", "AB");
dict.Add("B", "BC");
dict.Add("C", "DE");
dict.Add("D", "de");
dict.Add("e", "FG"); // 'e' khác 'E'
dict.Add("F", "gh");
Console.WriteLine("Key/Value pairs...");
foreach (DictionaryEntry de in dict)
{
Console.WriteLine("Key = " + de.Key + ", Value = " + de.Value);
}
}
}
Kết quả
Key/Value pairs... Key = A, Value = AB Key = B, Value = BC Key = C, Value = DE Key = D, Value = de Key = e, Value = FG Key = F, Value = gh
Hành vi Case-Sensitive vs Case-Insensitive
| Hành động | Case-Sensitive (false) | Case-Insensitive (true) |
|---|---|---|
| Add("A", 1); Add("a", 2) | OK - 2 khóa riêng | ArgumentException - khóa trùng |
| dict["A"] | Trả về giá trị của "A" | Trả về giá trị của "A" hoặc "a" |
| Contains("a") | False (nếu chỉ có "A") | True (nếu có "A") |
| Remove("a") | False (nếu chỉ có "A") | True (xóa "A") |
Khi nào dùng case-sensitive?
- Khóa là mã định danh (ID, code, username) cần phân biệt chính xác
- Dữ liệu phân biệt chữ hoa/thường theo bản chất (base64, hash, token)
- Tương tác với hệ thống case-sensitive (Linux filesystem, database)
Khuyến nghị hiện đại
// Dictionary generic với IEqualityComparer tùy chỉnh var dict = new Dictionary<string, string>(StringComparer.Ordinal); // Case-sensitive var dict2 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); // Case-insensitive // StringComparer options: StringComparer.Ordinal // Case-sensitive, fast StringComparer.OrdinalIgnoreCase // Case-insensitive, fast StringComparer.CurrentCulture // Case-sensitive, culture-aware StringComparer.CurrentCultureIgnoreCase // Case-insensitive, culture-aware StringComparer.InvariantCulture // Case-sensitive, invariant culture StringComparer.InvariantCultureIgnoreCase // Case-insensitive, invariant culture