C#中的Dictionary.Count属性
C#中的Dictionary.Count属性获取字典中键/值对的数量。
语法
public int Count { get; }现在让我们看一个实现字典的例子。计数属性-
示例
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("元素计数 = "+dict.Count);
Console.WriteLine("\n键/值对...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
if (dict.ContainsValue("Angelina"))
Console.WriteLine("找到值!");
else
Console.WriteLine("字典里没有值!");
dict.Clear();
Console.WriteLine("清除键/值对...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("元素计数 = "+dict.Count);
}
}输出结果
这将产生以下输出-
元素计数 = 5 键/值对... Key = One, Value = Chris Key = Two, Value = Steve Key = Three, Value = Messi Key = Four, Value = Ryan Key = Five, Value = Nathan 字典里没有值! 清除键/值对... 元素计数 = 0
现在让我们来看另一个实现字典的例子。计数属性-
示例
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("元素计数 = "+dict.Count);
}
}输出结果
这将产生以下输出-
元素计数 = 5