C# 中使用字典Dictionary来存储键值对的数据。创建字典时需要定义键值对的类型,再添加字典元素时需要符合定义的键值对类型。
要使用Dictionary集合,需要导入C#泛型命名空间
System.Collections.Generic(程序集:mscorlib)
Dictionary的特性:
1、从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
2、任何键都必须是唯一的
3、键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值
4、Key和Value可以是任何类型
1. 创建一个字典例如,创建一个键值都是字符串类型的字典
Dictionary<string, string> EmployeeList = new Dictionary<string, string>(); 2. 添加元素到字典使用Add 方法添加元素
EmployeeList.Add("Mahesh Chand", "Programmer"); EmployeeList.Add("Praveen Kumar", "Project Manager"); EmployeeList.Add("Raj Kumar", "Architect"); EmployeeList.Add("Nipun Tomar", "Asst. Project Manager"); EmployeeList.Add("Dinesh Beniwal", "Manager");类似可以创建其它类型的字典,通过Add方法添加元素。
Dictionary<string, int> AuthorList = new Dictionary<string, int>(); AuthorList.Add("Mahesh Chand", 35); AuthorList.Add("Mike Gold", 25); AuthorList.Add("Praveen Kumar", 29); AuthorList.Add("Raj Beniwal", 21); AuthorList.Add("Dinesh Beniwal", 84); Dictionary<string, float> PriceList = new Dictionary<string, float>(3); PriceList.Add("Tea", 3.25f); PriceList.Add("Juice", 2.76f); PriceList.Add("Milk", 1.15f); 3. 检索键值使用KeyValuePair 检索键和值
foreach (KeyValuePair<string,string> kv in EmployeeList) { Console.WriteLine($"键:{kv.Key} -> 值: {kv.Value}"); }检索键:
foreach (var k in EmployeeList.Keys) { Console.WriteLine(k); }检索值:
foreach (var v in EmployeeList.Values) { Console.WriteLine(v); } 4. 字典常用属性Count, Keys and Values
Keys,Values 分别是键集合和值集合
Count属性 元素(键值对)的个数
Console.WriteLine(EmployeeList.Count); 输出值 5
5. 修改字典中某个元素的值 //修改前 Console.WriteLine(EmployeeList\["Mahesh Chand"\]); EmployeeList\["Mahesh Chand"\] = "ModfiyValue"; //修改后 Console.WriteLine(EmployeeList\["Mahesh Chand"\]);字典名称[“键名”] = 要修改的值
6. 字典中常用方法add, remove, find(ContainsKey,ContainsValue)
Add方法用于添加元素,上面已经演示过。
Remove 用于删除元素
EmployeeList.Remove(“Mahesh Chand”);
查询键是否存在,值是否存在字典中
if(EmployeeList.ContainsKey("Mahesh Chand")) { Console.WriteLine("包含键 Mahesh Chand"); } if (!EmployeeList.ContainsValue("CEO")) { Console.WriteLine("CEO NOT found"); }
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。 |