C#编程(五十三)----------字典Dictionary<TKey,TValue>

字典

关键字: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()方法的实现代码

 

posted on 2017-03-24 09:53  Sun‘刺眼的博客  阅读(1252)  评论(0编辑  收藏  举报

导航