C#中的字典是一种键值对的集合,用于存储和访问数据。字典类似于现实生活中的字典,其中每个词条都有一个唯一的键和对应的值。
以下是使用C#字典的一些常见方法:
-
创建字典: Dictionary
dictionary = new Dictionary (); -
添加键值对: dictionary.Add(key, value);
-
获取值: TValue value = https://www.yisu.com/ask/dictionary[key];
-
更新值: dictionary[key] = newValue;
-
检查键是否存在: bool exists = dictionary.ContainsKey(key);
-
删除键值对: dictionary.Remove(key);
-
迭代字典: foreach(KeyValuePair
pair in dictionary) { TKey key = pair.Key; TValue value = https://www.yisu.com/ask/pair.Value;> -
获取字典中的键或值: ICollection
keys = dictionary.Keys; ICollection values = dictionary.Values;
以上是一些基本的字典操作方法,根据需要可以使用其他方法来完成更复杂的操作。