Dictionary trong C# là một tập hợp các cặp khóa và giá trị. Đây là một lớp tập hợp generic trong namespace System.Collections.Generic.
Cú pháp
public class Dictionary<TKey, TValue>
Trong đó TKey là kiểu của khóa, TValue là kiểu của giá trị.
Ví dụ 1: Tạo Dictionary và thêm phần tử
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("Các cặp khóa/giá trị...");
foreach (KeyValuePair<string, string> res in dict) {
Console.WriteLine("Khóa = {0}, Giá trị = {1}", res.Key, res.Value);
}
}
}
Kết quả
Các cặp khóa/giá trị... Khóa = One, Giá trị = John Khóa = Two, Giá trị = Tom Khóa = Three, Giá trị = Jacob Khóa = Four, Giá trị = Kevin Khóa = Five, Giá trị = Nathan
Ví dụ 2: Xóa khóa khỏi Dictionary
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "Kagido");
dict.Add("Two", "Ngidi");
dict.Add("Three", "Devillers");
dict.Add("Four", "Smith");
dict.Add("Five", "Warner");
Console.WriteLine("Số lượng phần tử = " + dict.Count);
Console.WriteLine("Đang xóa một số khóa...");
dict.Remove("Four");
dict.Remove("Five");
Console.WriteLine("Số lượng phần tử (cập nhật) = " + dict.Count);
Console.WriteLine("\nCác cặp khóa/giá trị...");
foreach (KeyValuePair<string, string> res in dict) {
Console.WriteLine("Khóa = {0}, Giá trị = {1}", res.Key, res.Value);
}
Console.Write("\nTất cả các khóa..\n");
Dictionary<string, string>.KeyCollection allKeys = dict.Keys;
foreach (string str in allKeys) {
Console.WriteLine("Khóa = {0}", str);
}
}
}
Kết quả
Số lượng phần tử = 5 Đang xóa một số khóa... Số lượng phần tử (cập nhật) = 3 Các cặp khóa/giá trị... Khóa = One, Giá trị = Kagido Khóa = Two, Giá trị = Ngidi Khóa = Three, Giá trị = Devillers Tất cả các khóa.. Khóa = One Khóa = Two Khóa = Three