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

C#字典

2016-02-13 11:56 393 查看

需求

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

是什么

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

关键字

Dictionary

说明

C#的
Dictionary<Tkey,TValue>
类在内部维护两个数组来实现该功能。一个keys数组容纳要从其映射的键,另一个values容纳映射到的值。在
Dictionary<Tkey,TValue>
集合中插入键/值对时,将自动记录哪个键和哪个值关联,从而允许开发人员快速和简单地获取具有指定键的值。

注意

C#的
Dictionary<Tkey,TValue>
集合不能包含重复的键。调用Add方法添加键数组中已有的键将抛出异常。但是,如果使用方括号记法(类似给数组元素赋值)来添加键/值对,就不用担心异常——如果键已经存在,其值就会被新值覆盖。可用ContainKey方法测试
Dictionary<Tkey,TValue>
集合是否已包含特定的键。

Dictionary<Tkey,TValue>
集合内部采用一种稀疏数据结构,在有大量内存可用时才最高效。随着更多元素的插入,
Dictionary<Tkey,TValue>
集合可能快速消耗大量内存。

用foreach遍历
Dictionary<Tkey,TValue>
集合返回一个
KeyValuePair<Tkey,TValue>
。该结构包含数据项的键和值拷贝,可通过Key和Value属性防蚊每个元素。元素是只读的,不能用它们修改
Dictionary<Tkey,TValue>
集合中的数据。

怎么用

下面通过以学生学号和姓名为键/值对为例

初始化

Dictionary<string,string> students=new Dictionary<string,string>();


插入

students.Add ("S001","张三");
students.Add ("S002","李四");
students["S003"]="王五";


删除

students.Remove ("S000");


修改

students["S002"]="李斯";


查询

单独查询

Debug.Log (students["S000"]);




遍历所有

foreach(KeyValuePair<string,string> stu in students)
Debug.Log ("Key:"+stu.Key+"  Name:"+stu.Value);




遍历Key

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




遍历Value

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




转载请注明出处:http://blog.csdn.net/ylbs110/article/details/50658740

完整代码

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MyDictionary : MonoBehaviour {

Dictionary<string,string> students=new Dictionary<string,string>();

void Start () {
students.Add ("S000","待删除");
students.Add ("S001","张三");
students.Add ("S002","李四");
students["S003"]="王五";

students["S002"]="李斯";

Debug.Log (students["S000"]);

students.Remove ("S000");

foreach(KeyValuePair<string,string> stu in students)
Debug.Log ("Key:"+stu.Key+"  Name:"+stu.Value);

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

foreach (string value in students.Values)
Debug.Log (value);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: