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()方法的实现代码
C#编程(五十三)----------字典Dictionary<TKey,TValue>的更多相关文章
- C#中数组、集合(ArrayList)、泛型集合List<T>、字典(dictionary<TKey,TValue>)全面对比
C#中数组.集合(ArrayList).泛型集合List<T>.字典(dictionary<TKey,TValue>)全面对比 为什么把这4个东西放在一起来说,因为c#中的这4 ...
- C# 字典 Dictionary<Tkey,Tvalue>
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来.我们都知道计算机技术发展日新月异,速度惊人的快,你我稍不留神,就会被慢慢淘汰!因此:每日不间断的学习是避免被 ...
- C# .Net 中字典Dictionary<TKey,TValue>泛型类 学习浅谈
一.综述: Dictionary<TKey,TValue>是在 .NET Framework 2.0 版中是新增的.表示键值对的集合,Dictionary<TKey,TValue&g ...
- C#字典 Dictionary<Tkey,Tvalue> 之线程安全问题 ConcurrentDictionary<Tkey,Tvalue> 多线程字典
ConcurrentDictionary<Tkey,Tvalue> Model #region 程序集 mscorlib, Version=4.0.0.0, Culture=neutra ...
- c# 扩展方法奇思妙用基础篇五:Dictionary<TKey, TValue> 扩展
Dictionary<TKey, TValue>类是常用的一个基础类,但用起来有时确不是很方便.本文逐一讨论,并使用扩展方法解决. 向字典中添加键和值 添加键和值使用 Add 方法,但很多 ...
- .net框架-字典对象 Hashtable & Dictionary<TKey,TValue> & SortedList
字典对象: 字典对象是表示键值对的集合 字典对象有Hashtable(.net 1.0)及其泛型版本Dictionary<TKey,TValue> 字典对象还包括SortedList及其泛 ...
- 泛型与非泛型集合类的区别及使用例程,包括ArrayList,Hashtable,List<T>,Dictionary<Tkey,Tvalue>,SortedList<Tkey,Tvalue>,Queue<T>,Stack<T>等
泛型与非泛型集合类在C#程序中是非常重要的一个基础概念,这里列一个表来进行对比: 非泛型集合类 泛型集合类 描述 ArrayList List<T> 表示具有动态大小的对象数组 Hasht ...
- Dictionary<TKey, TValue> 类
C# Dictionary<TKey, TValue> 类 Dictionary<TKey, TValue> 泛型类提供了从一组键到一组值的映射.字典中的每个添加项都由一个值及 ...
- Dictionary<Tkey.TValue>与SortedList
一.概述 表示Key/Value集合,可以添加删除元素,允许按Key来访问元素.是Hashtable的泛型等效类. 它需要一个相等实现来确定键是否相等,可以使用实现了IEqualityComparer ...
随机推荐
- selnium远程机上传图片遇到的坑
一般上传图片方法采取方案如下: input标签的file类型上传图片,使用对象的sendkeys+路径方法 使用js注入,再用使用对象的sendkeys+路径方法 使用autolt生成的exe,打开对 ...
- 今天我碰到了由于web.xml文件表头信息导致润乾报表启动失败的问题,解决方案如下
下面是从2.3,2.4.2.5 3.0集中版本的web.xml头信息的细节,当发现系统启动不报错但是该生成的功能没有正常生成,特别是在这次配置润乾报表的时候发现用2.4版本的时候,在web.xml中配 ...
- kafka在zookeeper中存储结构
1.topic注册信息 /brokers/topics/[topic] : 存储某个topic的partitions所有分配信息 Schema: { "version": ...
- NOIP2018 货币系统
题面 思路 先分析一下,a集合的子集肯定不存在可以用它来表示的数,a集合是不能够表示的. 所以问题简化了成为选出a的一个子集(个数最少),能够表达a集合所有能表达的数. 接下来继续分析 如:1 2 4 ...
- django中的view测试和models测试样例
感觉用model_mommy比factory_boy要好些. 如果Models.py如下: from django.db import models from django.contrib.auth. ...
- django用户系统的测试,蛮不错的。
https://blog.csdn.net/orangleliu/article/details/51944758 这个很实用 https://www.cnblogs.com/yanhuidj/p/1 ...
- python控制selenium点击登录按钮时报错 unknown error: Element is not clickable at point
利用python控制selenium进行一个网页的登录时报错: C:\Users\Desktop\selenium\chrome>python chrome.py selenium.common ...
- 【Java】 大话数据结构(10) 查找算法(1)(顺序、二分、插值、斐波那契查找)
本文根据<大话数据结构>一书,实现了Java版的顺序查找.折半查找.插值查找.斐波那契查找. 注:为与书一致,记录均从下标为1开始. 顺序表查找 顺序查找 顺序查找(Sequential ...
- miniblink+golang开发windows gui应用
golang的优点自不必说了,这么好的语言怎么能缺少界面库呢?所以我使用miniblink开发了一个可以用html,css,js开发界面的浏览器,通过它你能为你的golang开发简单的界面.说白了其实 ...
- QT5:使用QFile类读写文本乱码
我用的是QT5的QFile类实现的