美文网首页
重温 C# 字典Dictionary类

重温 C# 字典Dictionary类

作者: Ritchie_Li | 来源:发表于2022-05-27 15:46 被阅读0次

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");

   }

相关文章

网友评论

      本文标题:重温 C# 字典Dictionary类

      本文链接:https://www.haomeiwen.com/subject/crwmprtx.html