Phương thức Dictionary.Clear() trong C# xóa tất cả các cặp khóa/giá trị khỏi Dictionary<TKey,TValue>.
Cú pháp
public void Clear();
Ví dụ 1
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("Số lượng phần 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);
}
dict.Clear();
Console.WriteLine("Đã xóa 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);
}
Console.WriteLine("Số lượng phần tử bây giờ = " + dict.Count);
}
}
Kết quả
Số lượng phần tử = 5 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 Đã xóa các cặp khóa/giá trị... Số lượng phần tử bây giờ = 0
Ví dụ 2: Thêm rồi xóa
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("Số lượng phần tử = " + dict.Count);
dict.Add("Six", "Anne");
dict.Add("Seven", "Katoe");
Console.WriteLine("Số lượng phần tử (cập nhật) = " + dict.Count);
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);
}
dict.Clear();
Console.WriteLine("Đã xóa 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ả
Số lượng phần tử = 5 Số lượng phần tử (cập nhật) = 7 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 Khóa = Six, Giá trị = Anne Khóa = Seven, Giá trị = Katoe Đã xóa các cặp khóa/giá trị...