C# 中的字典方法
csharpprogrammingserver side programming
字典是 C# 中的键和值的集合。Dictionary<TKey, TValue> 包含在 System.Collection.Generics 命名空间中。
以下是方法 −
Sr.No | 方法 &说明 |
---|---|
1 | Add 在 Dictionary 中添加键值对 |
2 | Clear() 删除所有键和值 |
3 | Remove 删除具有指定键的元素。 |
4 | ContainsKey 检查 Dictionary<TKey, TValue> 中是否存在指定的键。 |
5 | ContainsValue 检查 Dictionary<TKey, TValue>。 |
6 | Count 计算键值对的数量。 |
7 | Clear 从 Dictionary<TKey, TValue> 中删除所有元素。 |
让我们看看如何将元素添加到 Dictionary 中并显示计数。
示例
using System; using System.Collections.Generic; public class Demo { public static void Main() { IDictionary<int, int> d = new Dictionary<int, int>(); d.Add(1,97); d.Add(2,89); d.Add(3,77); d.Add(4,88); d.Add(5,78); d.Add(6,98); Console.WriteLine(d.Count); } }
输出
6