C#字典

需求

通常情况下,我们可以通过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); 

遍历Key

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

遍历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);
    }
} 
  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值