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); } }
相关文章推荐
- C#发送邮件时提示:“不允许使用邮箱名称。服务器响应为:”的错误解决办法
- C#里面Attribute的使用方法
- C# 的三种序列化方法
- C#事件触发机制
- c#基本知识:泛型集合的使用
- C#机房重构——万事开头难(一)
- Atitit. C#.net clr 2.0 4.0新特性
- Atitit. C#.net clr 2.0 4.0新特性
- Atitit. C#.net clr 2.0 4.0新特性
- C#成神之路<18> C#使用磁盘数据文件(2)
- CSharpGL(13)用GLSL实现点光源(point light)和平行光源(directional light)的漫反射(diffuse reflection)
- [C# 基础知识梳理系列]专题六:泛型基础篇——为什么引入泛型
- C#中的继承与多态还有接口
- C# 正则表达式总结
- C#成神之路<17> C#使用磁盘数据文件(1)
- C#中yield关键字用法(以及delegate/Lambde/Linq之间的关系)
- C#获取存储过程的 Return返回值和Output输出参数值
- 造轮子:c#删除 list中的元素
- C# 中的委托和事件
- C#寒假学习笔记(4)