关键字:C# Dictionary 字典 
作者:txw1958
原文:http://www.cnblogs.com/txw1958/archive/2012/11/07/csharp-dictionary.html

说明
    必须包含名空间System.Collection.Generic 
    Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值) 
    键必须是唯一的,而值不需要唯一的 
    键和值都可以是任何类型(比如:string, int, 自定义类型,等等) 
    通过一个键读取一个值的时间是接近O(1) 
    键值对之间的偏序可以不定义

使用方法

  1. //定义
  2. Dictionary<string, string> openWith = new Dictionary<string, string>();
  1. //添加元素
  2. openWith.Add("txt", "notepad.exe");
  3. openWith.Add("bmp", "paint.exe");
  4. openWith.Add("dib", "paint.exe");
  5. openWith.Add("rtf", "wordpad.exe");
  1. //取值
  2. Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
  1. //更改值
  2. openWith["rtf"] = "winword.exe";
  3. Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
  1. //遍历key
  2. foreach (string key in openWith.Keys)
  3. {
  4. Console.WriteLine("Key = {0}", key);
  5. }
  1. //遍历value
  2. foreach (string value in openWith.Values)
  3. {
  4. Console.WriteLine("value = {0}", value);
  5. }
  6.  
  7. //遍历value, Second Method
  8. Dictionary<string, string>.ValueCollection valueColl = openWith.Values;
  9. foreach (string s in valueColl)
  10. {
  11. Console.WriteLine("Second Method, Value = {0}", s);
  12. }
  1. //遍历字典
  2. foreach (KeyValuePair<string, string> kvp in openWith)
  3. {
  4. Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
  5. }
  1. //添加存在的元素
  2. try
  3. {
  4. openWith.Add("txt", "winword.exe");
  5. }
  6. catch (ArgumentException)
  7. {
  8. Console.WriteLine("An element with Key = \"txt\" already exists.");
  9. }
  1. //删除元素
  2. openWith.Remove("doc");
  3. if (!openWith.ContainsKey("doc"))
  4. {
  5. Console.WriteLine("Key \"doc\" is not found.");
  6. }
  1. //判断键存在
  2. if (openWith.ContainsKey("bmp")) // True
  3. {
  4. Console.WriteLine("An element with Key = \"bmp\" exists.");
  5. }
  1. //参数为其它类型
  2. Dictionary<int, string[]> OtherType = new Dictionary<int, string[]>();
  3. OtherType.Add(, "1,11,111".Split(','));
  4. OtherType.Add(, "2,22,222".Split(','));
  5. Console.WriteLine(OtherType[][]);

参数为自定义类型

首先定义类

  1. class DouCube
  2. {
  3. public int Code { get { return _Code; } set { _Code = value; } } private int _Code;
  4. public string Page { get { return _Page; } set { _Page = value; } } private string _Page;
  5. }

然后

  1. //声明并添加元素
  2. Dictionary<int, DouCube> MyType = new Dictionary<int, DouCube>();
  3. for (int i = ; i <= ; i++)
  4. {
  5. DouCube element = new DouCube();
  6. element.Code = i * ;
  7. element.Page = "http://www.doucube.com/" + i.ToString() + ".html";
  8. MyType.Add(i, element);
  9. }
  1. //遍历元素
  1. foreach (KeyValuePair<int, DouCube> kvp in MyType)
  2. {
  3. Console.WriteLine("Index {0} Code:{1} Page:{2}", kvp.Key, kvp.Value.Code, kvp.Value.Page);
  4. }

常用属性

名称    说明
    Comparer     获取用于确定字典中的键是否相等的 IEqualityComparer<T>。
    Count        获取包含在 Dictionary<TKey, TValue> 中的键/值对的数目。
    Item         获取或设置与指定的键相关联的值。
    Keys         获取包含 Dictionary<TKey, TValue> 中的键的集合。
    Values       获取包含 Dictionary<TKey, TValue> 中的值的集合。

常用方法
    名称    说明
    Add                 将指定的键和值添加到字典中。
    Clear               从 Dictionary<TKey, TValue> 中移除所有的键和值。
    ContainsKey         确定 Dictionary<TKey, TValue> 是否包含指定的键。
    ContainsValue       确定 Dictionary<TKey, TValue> 是否包含特定值。
    Equals(Object)      确定指定的 Object 是否等于当前的 Object。 (继承自 Object。)
    Finalize            允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
    GetEnumerator       返回循环访问 Dictionary<TKey, TValue> 的枚举器。
    GetHashCode         用作特定类型的哈希函数。 (继承自 Object。)
    GetObjectData       实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary<TKey, TValue> 实例所需的数据。
    GetType             获取当前实例的 Type。 (继承自 Object。)
    MemberwiseClone     创建当前 Object 的浅表副本。 (继承自 Object。)
    OnDeserialization    实现 System.Runtime.Serialization.ISerializable 接口,并在完成反序列化之后引发反序列化事件。
    Remove              从 Dictionary<TKey, TValue> 中移除所指定的键的值。
    ToString            返回表示当前对象的字符串。 (继承自 Object。)
    TryGetValue         获取与指定的键相关联的值。

C#中Dictionary的介绍的更多相关文章

  1. .NET中Dictionary<TKey, TValue>浅析

    .NET中Dictionary<TKey, Tvalue>是非常常用的key-value的数据结构,也就是其实就是传说中的哈希表..NET中还有一个叫做Hashtable的类型,两个类型都 ...

  2. AutoMapper之ABP项目中的使用介绍

    最近在研究ABP项目,昨天写了Castle Windsor常用介绍以及其在ABP项目的应用介绍 欢迎各位拍砖,有关ABP的介绍请看阳光铭睿 博客 AutoMapper只要用来数据转换,在园里已经有很多 ...

  3. C#中Dictionary<TKey,TValue>排序方式

    自定义类: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Sy ...

  4. iOS开发UI篇—iPad开发中得modal介绍

    iOS开发UI篇—iPad开发中得modal介绍 一.简单介绍 说明1: 在iPhone开发中,Modal是一种常见的切换控制器的方式 默认是从屏幕底部往上弹出,直到完全盖住后面的内容为止 说明2: ...

  5. C#中Dictionary小记

    使用C#中Dictionary的一下细节小记: 一.Dictionary.Add(key,value) 与 Dictionary[key]=value的区别: 如果Dictionary中已经有了key ...

  6. objective-c 中的关联介绍

    objective-c 中的关联介绍 转载请注明CSDN博客上的出处: http://blog.csdn.net/daiyibo123/article/details/46471993 如何设置关联 ...

  7. ORACLE 中的 锁 介绍

    ORACLE 中的 锁 介绍 Oracle数据库支持多个用户同时与数据库进行交互,每个用户都可以同时运行自己的事务,从而也需要对并发访问进行控制.Oracle也是用“锁”的机制来防止各个事务之间的相互 ...

  8. C#中Dictionary的用法

    在C#中,Dictionary提供快速的基于兼职的元素查找.他的结构是这样的:Dictionary<[key], [value]> ,当你有很多元素的时候可以使用它.它包含在System. ...

  9. Android中Snackbar的介绍以及使用

    Android中Snackbar的介绍以及使用 介绍 Snackbar可以说是Toast的升级版,不仅有显示信息的功能,还可以添加一个Action,实现点击功能,可以右滑删除. 效果图 Snackba ...

随机推荐

  1. Django 数据库读写分离 分库分表

    多个数据库 配置: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BA ...

  2. Pandas 数据清洗常用篇

    一.缺失值 sklearn中的preprocessing下有imputer,可进官方文档参考.这里主讲pandas. 拿到数据,一般先检查是否有缺失值,用isnul()或notnull(). 再决定d ...

  3. 分布式存储ceph——(6)ceph 讲解

    一.Ceph简介: Ceph是一种为优秀的性能.可靠性和可扩展性而设计的统一的.分布式文件系统.ceph 的统一体现在可以提供文件系统.块存储和对象存储,分布式体现在可以动态扩展.在国内一些公司的云环 ...

  4. 一入OI深似海 3 —— 纪念我最后一次PJ(上)

    其实在比赛前一天中午上车前, 我还在机房打 I wanna, 感觉就是去杭州旅游的. 诶,还真是这样! 我和jwj在绍兴服务区买了金拱门, 拎着吃的回到车上的时候, 迎面而来羡慕的小眼神. 下午很早就 ...

  5. HTTP协议与TCP/IP协议

    OSI 是7层         TCP/IP 协议是 4层. OIS 包括的层 从底到上依次为 1.物理层 2.数据链路层 3.网络层 4.传输层 5.会话层 6.表示层 7.应用层 TCP/IP  ...

  6. linux定时备份学习笔记

    1.iterm2链接远程中文乱码 shh端vi ~/.bash_profile export LC_CTYPE=en_US.UTF-8 source ~/.bash_profile   2.WARNI ...

  7. XXXX is not in the sudoers file. This incident will be reported解决方法

    假设你用的是Red Hat系列(包括Fedora和CentOS)的Linux系统.当你执行sudo命令时可能会提示“某某用户 is not in the sudoers file.  This inc ...

  8. RedisCache 缓存

    /// <summary> /// 这是包装过公用的,用于本站而已. /// </summary> /// <author>rixiao</author> ...

  9. Leetcode 5

    HashTable Easy 1. 136. Single Number 0与0异或是0,1与1异或也是0,那么我们会得到0 class Solution { public: int singleNu ...

  10. 存储类&作用域&生命周期&链接属性

    链接属性 (1)大家知道程序从源代码到最终可执行程序,经历的过程:编译.链接. (2)编译阶段就是把源代码搞成.o目标文件,目标文件里面有很多符号和代码段.数据段.bss段等分段.符号就是编程中的变量 ...