您的位置:首页 > 编程语言 > C#

C#自用基础知识点-字典

2020-07-30 12:15 886 查看

1. 使用字典原因

通常情况下,我们可以通过int类型的索引号来从数组或者list集合中查询所需的数据。
但是如果情况稍微复杂一点:索引号是非int型数据比如string或其他类型该如何操作呢。这个时候我们就可以使用字典了。

2. 什么是字典

顾名思义,字典是一种让我们可以通过索引号查询到特定数据的数据结构类型。第一个参数是键,第二个参数是值

关键字 DIctionary

3. 实例

Dictionary<string,string>students=newDictionary<string,string>();
插入:

students.Add ("S001","张三");

students.Add ("S002","李四");

students["S003"]="王五";

删除:

students.Remove ("S000"); //直接删除建即可

修改:

直接复制即可    students["S003"]="王五";

提取元素的方法

string a = students[“s0003”];

查询:

foreach(KeyValuePair<string,string> stu in students)  //查询所Keys 和Value
Debug.Log ("Key:"+stu.Key+"  Name:"+stu.Value);

foreach (string value in students.Values)
Debug.Log (value);

foreach (string key in students.Keys)
Debug.Log (key);

4.扩展

由作家的名字查找到作家的作品

首先
定义一个建为字符串(名字),值为字符串类型的动态数组(作品):

Dictionary<string,list<string>> writer = new Dictionary<string,list<string>>();

根据键找到相应的list动态数组

list<string> liucixin = new list<string>();
writer.add("刘慈欣",liucixin);

向list中添加刘慈欣的作品:

liucixin.add("三体");

输出:

foreach(KeyValuePair<strig,list<string>> i in writer)
{

Console.WriteLine(i.key);//输出作者
foreach(string e in i.value)//输出作品
{
Console.Write(e);//不用换行
}

}

ps:KeyValuePair

KeyValuePair<TKey,TValue>的用法。结构体,定义可设置或检索的键/值对。也就是说我们可以通过
它记录一个键/值对这样的值。 使用KeyValuePair记录枚举字典中的键/值,ke.Key, ke.Value获取键对应的值
foreach(KeyValuePair<char,int> ke in dic) {
Console.WriteLine("{0}出现{1}次\n",ke.Key,ke.Value); }

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: