Giới thiệu
Để lấy số lượng cặp khóa/giá trị trong StringDictionary, bạn sử dụng thuộc tính Count. Dưới đây là các ví dụ minh họa.
Ví dụ 1
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringDictionary strDict = new StringDictionary();
strDict.Add("1", "One");
strDict.Add("2", "Two");
strDict.Add("3", "Three");
strDict.Add("4", "Four");
Console.WriteLine("Các cặp khóa-giá trị của StringDictionary...");
IEnumerator demoEnum = strDict.GetEnumerator();
DictionaryEntry d;
while (demoEnum.MoveNext())
{
d = (DictionaryEntry)demoEnum.Current;
Console.WriteLine("Khóa = " + d.Key + ", Giá trị = " + d.Value);
}
Console.WriteLine("Số lượng cặp khóa-giá trị... " + strDict.Count);
}
}
Kết quả
Các cặp khóa-giá trị của StringDictionary... Khóa = 1, Giá trị = One Khóa = 2, Giá trị = Two Khóa = 3, Giá trị = Three Khóa = 4, Giá trị = Four Số lượng cặp khóa-giá trị... 4
Ví dụ 2: Hai StringDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringDictionary strDict1 = new StringDictionary();
strDict1.Add("A", "John");
strDict1.Add("B", "Andy");
strDict1.Add("C", "Tim");
strDict1.Add("D", "Ryan");
strDict1.Add("E", "Kevin");
strDict1.Add("F", "Katie");
strDict1.Add("G", "Brad");
Console.WriteLine("Các phần tử của StringDictionary1...");
foreach (DictionaryEntry de in strDict1)
{
Console.WriteLine(de.Key + " " + de.Value);
}
Console.WriteLine("Số lượng cặp khóa-giá trị của StringDictionary1... " + strDict1.Count);
StringDictionary strDict2 = new StringDictionary();
strDict2.Add("1", "A");
strDict2.Add("2", "B");
strDict2.Add("3", "C");
strDict2.Add("4", "D");
strDict2.Add("5", "E");
Console.WriteLine("\nCác cặp khóa-giá trị của StringDictionary2...");
IEnumerator demoEnum = strDict2.GetEnumerator();
DictionaryEntry d;
while (demoEnum.MoveNext())
{
d = (DictionaryEntry)demoEnum.Current;
Console.WriteLine("Khóa = " + d.Key + ", Giá trị = " + d.Value);
}
Console.WriteLine("Số lượng cặp khóa-giá trị của StringDictionary2... " + strDict2.Count);
}
}
Kết quả
Các phần tử của StringDictionary1... A John B Andy C Tim D Ryan E Kevin F Katie G Brad Số lượng cặp khóa-giá trị của StringDictionary1... 7 Các cặp khóa-giá trị của StringDictionary2... Khóa = 1, Giá trị = A Khóa = 2, Giá trị = B Khóa = 3, Giá trị = C Khóa = 4, Giá trị = D Khóa = 5, Giá trị = E Số lượng cặp khóa-giá trị của StringDictionary2... 5
Lưu ý: StringDictionary chỉ chấp nhận khóa và giá trị là chuỗi, và khóa không phân biệt chữ hoa/thường.