Thuộc tính Dictionary.Count trong C# lấy số lượng cặp khóa/giá trị trong Dictionary.
Cú pháp
public int Count { get; }
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", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
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);
}
if (dict.ContainsValue("Angelina"))
Console.WriteLine("Tìm thấy giá trị!");
else
Console.WriteLine("Giá trị không có trong dictionary!");
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ị = Chris Khóa = Two, Giá trị = Steve Khóa = Three, Giá trị = Messi Khóa = Four, Giá trị = Ryan Khóa = Five, Giá trị = Nathan Giá trị không có trong dictionary! Đã xóa các cặp khóa/giá trị... Số lượng phần tử bây giờ = 0
Ví dụ 2
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "David");
dict.Add("Two", "Brian");
dict.Add("Three", "Paul");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine("Số lượng phần tử = " + dict.Count);
}
}
Kết quả
Số lượng phần tử = 5