字典

关键字:Dicitionary

说明:

必须包含命名空间System.Collection.Generic

Dictionary里面的每一个元素都是一个键值对(由两个元组组成:键和值).

键必须是唯一的,而值不需要唯一的.

键和值都可以是任意类型(例如:string,int,自定义类型,等等)

通过一个键读取一个值的事件是接近O(1)

键值对之间的偏序可以不定义

使用案例:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections.Generic;

namespace 字典

{

class Program

{

static void Main(string[] args)

{

//定义

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

//添加元素

openWith.Add("txt", "notepad.exe");

openWith.Add("bmp", "paint.exe");

openWith.Add("dib", "paint.exe");

openWith.Add("rtf", "wordpad.exe");

//取值

Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

//更改值

openWith["rtf"] = "winword.exe";

//查看

Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

//遍历Key

foreach (var item in openWith.Keys)

{

Console.WriteLine("Key = {0}", item);

}

//遍历value

foreach (var item in openWith.Values)

{

Console.WriteLine("value = {0}", item);

}

//遍历value的第二种方法

Dictionary<string, string>.ValueCollection valueColl = openWith.Values;

foreach (var item in valueColl)

{

Console.WriteLine("value = {0}", item);

}

//遍历字典

foreach (KeyValuePair<string, string> item in openWith)

{

Console.WriteLine("key = {0} , value = {1} ", item.Key, item.Value);

}

//添加存在的元素

try

{

openWith.Add("txt", "winword.exe");

}

catch (ArgumentException)

{

Console.WriteLine("An element with Key = \"txt\" already exists.");

}

//删除元素

openWith.Remove("doc");

if (!openWith.ContainsKey("doc"))

{

Console.WriteLine("Key \"doc\" is not found.");

}

//判断键存在

if (openWith.ContainsKey("bmp"))

{

Console.WriteLine("An element with Key = \"bmp\" exists.");

}

//参数为其他类型

Dictionary<int, string[]> OtherType = new Dictionary<int, string[]>();

OtherType.Add(1, "1,11,111".Split(','));

OtherType.Add(2, "2,22,222".Split(','));

Console.WriteLine("其他类型 : " + OtherType[1][2]);

//参数为自定义类型

//声明并添加元素

Dictionary<int, DouCube> MyType = new Dictionary<int, DouCube>();

for (int i = 1; i <= 9; i++)

{

DouCube element = new DouCube();

element.Code = i * 100;

element.Page = "http://www.doucube.com/" + i.ToString() + ".html";

MyType.Add(i, element);

}

//遍历元素

foreach (KeyValuePair<int, DouCube> kvp in MyType)

{

Console.WriteLine("Index {0} Code:{1} Page:{2}", kvp.Key, kvp.Value.Code, kvp.Value.Page);

}

}

}

public class DouCube

{

public int Code { get { return _Code; } set { _Code = value; } } private int _Code;

public string Page { get { return _Page; } set { _Page = value; } } private string _Page;

}

}

常用属性

名称

说明

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

返回表示当前对象的字符串

TryGetValue

获取与指定的键相关联的值.

总结Dictionary:

字典也称为映射表或散列表,主要特定是可以根据键快速查找值,也可以自由删除添加元素,在删除添加时,不会像列表一样,移动之后的所有元素,产生内存的开销.

.NET中提供了几个字典,可以使用最主要的类是Dictionary<TKey,TValue>,这个类与我们上面说的SoreedList用法完全一样.

键的类型:

用作字典中键的类型必须重写object类中的GetHashCode()方法,只要字典类需要确定元素的位置,就要调用本方法.

字典内部通过调用这个方法的返回值,来计算产生散列(这是一个算法,不去研究,它涉及一个素数),所以字典的容量是一个素数.

GetHashCode()方法的实现需要遵循以下几点:

1.相同的对象应总是返回相同的值

2.不同的对象可以返回相同的值

3.应执行额比较快,计算的开销不大

4.不能抛出异常

5.应至少使用一个实例字段

6.散列码值应平均分布在int可以存储的整个数字区域

7.散列码最好在对象的生存期中不发生变化

提示:字典的性能取决于GetHashCode()方法的实现代码

C#编程(五十三)----------字典Dictionary<TKey,TValue>的更多相关文章

  1. C#中数组、集合(ArrayList)、泛型集合List<T>、字典(dictionary<TKey,TValue>)全面对比

    C#中数组.集合(ArrayList).泛型集合List<T>.字典(dictionary<TKey,TValue>)全面对比 为什么把这4个东西放在一起来说,因为c#中的这4 ...

  2. C# 字典 Dictionary<Tkey,Tvalue>

    最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来.我们都知道计算机技术发展日新月异,速度惊人的快,你我稍不留神,就会被慢慢淘汰!因此:每日不间断的学习是避免被 ...

  3. C# .Net 中字典Dictionary<TKey,TValue>泛型类 学习浅谈

    一.综述: Dictionary<TKey,TValue>是在 .NET Framework 2.0 版中是新增的.表示键值对的集合,Dictionary<TKey,TValue&g ...

  4. C#字典 Dictionary<Tkey,Tvalue> 之线程安全问题 ConcurrentDictionary<Tkey,Tvalue> 多线程字典

    ConcurrentDictionary<Tkey,Tvalue>  Model #region 程序集 mscorlib, Version=4.0.0.0, Culture=neutra ...

  5. c# 扩展方法奇思妙用基础篇五:Dictionary<TKey, TValue> 扩展

    Dictionary<TKey, TValue>类是常用的一个基础类,但用起来有时确不是很方便.本文逐一讨论,并使用扩展方法解决. 向字典中添加键和值 添加键和值使用 Add 方法,但很多 ...

  6. .net框架-字典对象 Hashtable & Dictionary<TKey,TValue> & SortedList

    字典对象: 字典对象是表示键值对的集合 字典对象有Hashtable(.net 1.0)及其泛型版本Dictionary<TKey,TValue> 字典对象还包括SortedList及其泛 ...

  7. 泛型与非泛型集合类的区别及使用例程,包括ArrayList,Hashtable,List<T>,Dictionary<Tkey,Tvalue>,SortedList<Tkey,Tvalue>,Queue<T>,Stack<T>等

    泛型与非泛型集合类在C#程序中是非常重要的一个基础概念,这里列一个表来进行对比: 非泛型集合类 泛型集合类 描述 ArrayList List<T> 表示具有动态大小的对象数组 Hasht ...

  8. Dictionary<TKey, TValue> 类

    C# Dictionary<TKey, TValue> 类 Dictionary<TKey, TValue> 泛型类提供了从一组键到一组值的映射.字典中的每个添加项都由一个值及 ...

  9. Dictionary<Tkey.TValue>与SortedList

    一.概述 表示Key/Value集合,可以添加删除元素,允许按Key来访问元素.是Hashtable的泛型等效类. 它需要一个相等实现来确定键是否相等,可以使用实现了IEqualityComparer ...

随机推荐

  1. Entity Framework 6.1.0 Tools for Visual Studio 2012 & 2013

    http://www.microsoft.com/en-us/download/confirmation.aspx?id=40762

  2. 【前端vue开发】vue开发总结

  3. javascript-词法分析解析

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. 树链刨分(class版)

    class版树链剖(刨)分 感谢沙华大佬的赞助 其实没什么太大变化,就是用了几次一顿乱指... CODE: #include<iostream> #include<cstdio> ...

  5. ***PHP $_FILES函数详解 + PHP文件上传 move_uploaded_file() 参数的正确写法

    PHP $_FILES函数详解 在PHP中上传一个文件建一个表单要比ASP中灵活得多.具体的看代码. 如:  复制代码代码如下: <form enctype="multipart/fo ...

  6. [转] 使用moment.js轻松管理日期和时间

    当前时间:moment().format('YYYY-MM-DD HH:mm:ss'); 2017-03-01 16:30:12 今天是星期几:moment().format('d'); 3 Unix ...

  7. oracle用户名小写时,利用sqlplus连接

    [oracle@upright92 ~]$ sqlplus / as sysdba SQL*Plus: Release 11.2.0.4.0 Production on Tue May 22 10:3 ...

  8. 移动端h5需要注意的一些事

    1.移动端点击a标签出现的背景色 a, a:hover, a:active, a:visited, a:link, a:focus { -webkit-tap-highlight-color: rgb ...

  9. AngularJS初始化静态模板

    AngularJS可以通过ng-app来自动初始化模块,也可以通过angular.bootstrap(document, [module])手动启动应用,不管用哪种方法,应用启动后,动态往dom树里面 ...

  10. hdu4055

    hdu4055 题意 给出一个长度为 n - 1 的字符串,要求构造一个包含数字 [1, n] 的排列,从第二位开始,'I' 表示当前位数字比前一位大,'D' 表示当前位数字比前一位小,'?' 表示可 ...