字典

关键字: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. 初始ASP.NET数据控件【续 DataList】

    DataList控件  DataList控件也是一个常用的数据绑定控件,相对于GridView控件虽然没它那么强大的功能,但是灵活性却很强势.因为其本身就是一个富有弹性的控件.DataList控件可以 ...

  2. Jmeter之逻辑控制器(Logic Controller)【转】

    Jmeter之逻辑控制器(Logic Controller) 前言: 1. Jmeter官网对逻辑控制器的解释是:“Logic Controllers determine the order in w ...

  3. free命令中的buffer和cached的比较(转)

    原文链接:https://www.jianshu.com/p/cd2dd59d1566 最近在搞监控,突然看到我系统的内存要用完了,赶紧登录服务器看看, ~]# dstat -m     16G内存就 ...

  4. keyspace notification(键空间通知)-待验证

    一.需求分析: 设置了生存时间的Key,在过期时能不能有所提示? 如果能对过期Key有个监听,如何对过期Key进行一个回调处理? 如何使用 Redis 来实现定时任务? 二.序言: 本文所说的定时任务 ...

  5. Python学习系列之(二)图解Windows8.1下安装Django

    一. 下载 去官网下载https://www.djangoproject.com/download/最新版,最新版本是1.6 二. 安装: 将下载下来的Django-1.6.tar.gz解压到D盘,接 ...

  6. python基础--模块使用

      一:模块介绍 模块分为三种: 自定义模块 内置标准模块(又称标准库) 开源模块 自定义模块使用 # -*- coding:utf-8 -*- __author__ = 'shisanjun' &q ...

  7. unit测试出现异常:Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.commons.util

    在进行单元测试时,测试出现异常 Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform ...

  8. Zookeeper集群搭建以及python操作zk

    一.Zookeeper原理简介 ZooKeeper是一个开放源码的分布式应用程序协调服务,它包含一个简单的原语集,分布式应用程序可以基于它实现同步服务,配置维护和命名服务等. Zookeeper设计目 ...

  9. 【OpenCV for Android】Android Studio JNI和NDK配置及采坑记录

    在配置好Android studio的OpenCV环境后,我们就可以通过Java代码调用OpenCV的API了,但是在通常情况下,用Java代码编写图像处理算法的运行效率是没有C++代码高的,在应用层 ...

  10. 关于 contentWindow, contentDocument

    没有永恒的技术只有变态的需求,没有好说的客户只有无奈的开发者, 如果iframe的出现是一个错误的话,iframe里边在来一个iframe那是错上加错,神话没有在远古的尘嚣中消失,却在怀具的今天不断上 ...