Mục đích
Thuộc tính Count của Dictionary<TKey, TValue> trả về số lượng cặp key-value hiện có trong từ điển.
Ví dụ 1: Thêm, đếm, duyệt và xóa
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Dictionary dict = new Dictionary();
dict.Add("One", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine($"Số phần tử: {dict.Count}");
Console.WriteLine("\nCác cặp Key/Value:");
foreach (KeyValuePair kvp in dict)
{
Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
}
// Kiểm tra tồn tại giá trị
Console.WriteLine($"\nCó 'Angelina'? {dict.ContainsValue("Angelina")}");
// Xóa tất cả
dict.Clear();
Console.WriteLine($"\nSau Clear(), Count = {dict.Count}");
}
}
Kết quả
Số phần tử: 5
Các cặp Key/Value:
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
Có 'Angelina'? False
Sau Clear(), Count = 0
Ví dụ 2: Chỉ đếm số phần tử
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Dictionary dict = new Dictionary();
dict.Add("One", "David");
dict.Add("Two", "Brian");
dict.Add("Three", "Paul");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine($"Số phần tử: {dict.Count}");
}
}
Kết quả
Số phần tử: 5
Lưu ý
Countlà thuộc tính chỉ đọc (read-only), độ phức tạp O(1).- Khác với
Capacity(chỉ có trong List, ArrayList), Dictionary không công khai Capacity. - Dùng
ContainsKey/ContainsValueđể kiểm tra tồn tại. - Thread-safe: Dictionary không thread-safe, dùng
ConcurrentDictionarycho đa luồng.