Dictionary使用(转)

1、要使用Dictionary集合,需要导入C#泛型命名空间
  System.Collections.Generic(程序集:mscorlib)
2、描述
   1)、从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
   2)、任何键都必须是唯一的
   3)、键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值
   4)、Key和Value可以是任何类型(string,int,custom class 等)
3、创建及初始化

   Dictionary<int, string> myDictionary = new Dictionary<int, string>();

4、添加元素

   myDictionary.Add("C#",0);
   myDictionary.Add("C++",1);
   myDictionary.Add("C",2);
   myDictionary.Add("VB",2);

5、查找元素By Key

  if(myDictionary.ContainsKey("C#"))
  {
    Console.WriteLine("Key:{0},Value:{1}", "C#", myDictionary["C#"]);
  }

6.遍历元素 By KeyValuePair

  foreach (KeyValuePair<string, int> kvp in myDictionary)
  {
    Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
  }

7、仅遍历键 By Keys 属性

  Dictionary<string, int>.KeyCollection keyCol = myDictionary.Keys;
  foreach (string key in keyCol/*string key in myDictionary.Keys*/)
  {
    Console.WriteLine("Key = {0}", key);
  }

8、仅遍历值By Valus属性

  Dictionary<string, int>.ValueCollection valueCol = myDictionary.Values;
  foreach (int value in valueCol)
  {
    Console.WriteLine("Value = {0}", value);
  }

9.移除指定的键值By Remove方法

  myDictionary.Remove("C#");
  if (myDictionary.ContainsKey("C#"))
  {
    Console.WriteLine("Key:{0},Value:{1}", "C#", myDictionary["C#"]);
  }
  else
  {
    Console.WriteLine("不存在 Key : C#");
}

在System.Collections.Generic命名空间中,与ArrayList相对应的泛型集合是List<T>,与 HashTable相对应的泛型集合是Dictionary<K,V>,其存储数据的方式与哈希表相似,通过键/值来保存元素,并具有泛型的全部特征,编译时检查类型约束,读取时无须类型转换。

  电话本存储的例子中,使用Dictionary<K,V>来存储电话本信息,代码如下:

Dictionary<string,TelNote> ht=new Dictionary<string,TelNote>();

  在Dictionary<K,V>声明中,“<string,TelNote>”中的string表示集合中Key的类型,TelNote表示Value的类型,定义Dictionary<K,V>泛型集合中的方法如下:

Dictionary<K,V> students=new Dictionary<K,V>();

  其中“K”为占位符,具体定义时用存储键“Key”的数据类型代替,“V”也是占位符,用元素的值“Value”的数据类型代替,这样就在定义该集合时,声明了存储元素的键和值的数据类型,保证了类型的安全性。
  Dictionary<K,V>中元素的操作方法与HashTable相似,添加元素,获取元素,删除元素,遍历集合元素的方法基本相同。

Dictionary<K,V>和HashTable的区别
Dictionary<K,V>和HashTable的相同点:添加元素,删除元素,通过键访问值的方法相同。
Dictionary<K,V>和HashTable的不同点:
Dictionary<K,V>对添加的元素具有类型约束,HashTable可添加任意类型的元素。
Dictionary<K,V>不需要装箱、拆箱操作,HashTable添加时装箱,读取时拆箱。

  在Dictionary<K,V>集合中,除了通过键获取值的方法外,还有一种TryGetValue(key)方法,可以通过键获取值,该方法返回值为布尔型,如果存在和键相对应的值,则返回true,否则返回false。避免了因获取不到相应值发生的异常。

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
//创建Dictionary<K,V>,然后添加元素
Dictionary < string, string > film = new Dictionary < string, string > ();
film.Add("韦小宝", "鹿鼎记");
film.Add("陆小凤", "陆小凤传奇");
film.Add("张无忌", "倚天屠龙记");
film.Add("杨过", "神雕侠侣");
film.Add("令狐冲", "笑傲江湖");
Console.WriteLine("集合现在的元素个数为{0}", film.Count);
film.Remove("杨过");
//遍历集合
Console.WriteLine("武侠电影的主角及电影名");
Console.WriteLine("/t主角/t电影");
foreach (KeyValuePair < string, string > kvp in film)
{
Console.WriteLine("/t{0}/t{1}", kvp.Key, kvp.Value);
}
//检查元素是否存在,如不存在,添加
if (!film.ContainsKey("段誉"))
{
film.Add("段誉", "天龙八部");
}
//获取键的集合
Dictionary < string, string > .KeyCollection keys = film.Keys;
//遍历键的集合
Console.WriteLine("受欢迎的武侠片中主角名");
foreach (string str in keys)
{
Console.WriteLine(str);
}
Dictionary < string, string > .ValueCollection values = film.Values;
//遍历值的集合
Console.WriteLine("最受欢迎的武侠片");
foreach (string strfilm in values)
{
Console.WriteLine(strfilm);
}
//遍历元素的另一种方法
Console.WriteLine("和哈希表相同的遍历元素方法");
foreach (string strname in film.Values)
{
Console.WriteLine(strname);
}
//获取键对应的值
string myfilm = film["令狐冲"];
Console.WriteLine("主角为令狐冲的电影名{0}", myfilm);
//获取键对应值的TryGetValue方法
string objfilm = string.Empty;
if (film.TryGetValue("段誉", out objfilm))
{
Console.WriteLine("主角为段誉的电影是{0}", objfilm);
}
else
Console.WriteLine("没有主角为段誉的电影");
Console.ReadKey();
}
}

  代码创建了一个Dictionary<K,V>集合,键和值的数据类型是string类型,后边代码的元素添加,删除都和哈希表处理方法相同,遍历元素时不需要进行数据类型强制转换。Dictionary<K,V>通过键取值的TryGetValue方法,此方法包括两个参数,一个是要查询的键,另一个是获取的值,注意值前面使用out关键字。

注意:使用TryGetValue方法时,参数一定要使用out关键字,否则编译失败。

原文链接:http://www.code-design.cn/article/20120210/csharp-generic-Collection-Dictionary.aspx

时间: 2024-08-10 15:11:29

Dictionary使用(转)的相关文章

C#中Dictionary的介绍

关键字:C# Dictionary 字典 作者:txw1958原文:http://www.cnblogs.com/txw1958/archive/2012/11/07/csharp-dictionary.html 说明    必须包含名空间System.Collection.Generic     Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)     键必须是唯一的,而值不需要唯一的     键和值都可以是任何类型(比如:string, int, 自定义类型,等等

c# 扩展方法奇思妙用基础篇五:Dictionary&lt;TKey, TValue&gt; 扩展

Dictionary<TKey, TValue>类是常用的一个基础类,但用起来有时确不是很方便.本文逐一讨论,并使用扩展方法解决. 向字典中添加键和值 添加键和值使用 Add 方法,但很多时候,我们是不敢轻易添加的,因为 Dictionary<TKey, TValue>不允许重复,尝试添加重复的键时 Add 方法引发 ArgumentException. 大多时候,我们都会写成以下的样子: var dict = new Dictionary<int, string>()

Linq在Array,List,Dictionary中的应用

Linq在Array,List,Dictionary中的应用 今天在实际工作中需要对array,list,dictionary进行排序,试一试linq,发现非常好用,代码如下: 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Text.RegularExpressions; 6 7 namespace Test 8 { 9 cl

.Net——缓存机制(一):利用Dictionary模拟缓存

在计算机的硬件设计中,有一个被反复使用的思想--缓存.同样,在软件设计中,这个思想也可以用来解决数据读取非常耗时带来的性能问题(当然,在时间和空间上,我们要寻找一个平衡点). 首先来看理想的缓存应该是怎么描述的: static Func<T, R> Cache<T, R>(Func<T, R> func) { var mem = new Dictionary<T, R>(); return x => { if (!mem.ContainsKey(x))

JavaScript如何创建dictionary对象

对于JavaScript来说,其自身的Array对象仅仅是个数组,无法提供通过关键字来获取保存的数据,jQuery源码中提供了一种非常好的方式来解决这个问题,先看一下源码: function createCache() { var keys = []; function cache(key, value) { // Use (key + " ") to avoid collision with native prototype // properties (see Issue #157

Dictionary Learning(字典学习、稀疏表示以及其他)

第一部分 字典学习以及稀疏表示的概要 字典学习(Dictionary Learning)和稀疏表示(Sparse Representation)在学术界的正式称谓应该是稀疏字典学习(Sparse Dictionary Learning).该算法理论包含两个阶段:字典构建阶段(Dictionary Generate)和利用字典(稀疏的)表示样本阶段(Sparse coding with a precomputed dictionary).这两个阶段(如下图)的每个阶段都有许多不同算法可供选择,每种

Learn Python 009: Dictionary

# create a dictionary students = {"Alice": 24, "Bob": 26, "Clark": 23, "Dan": 28, "Emma": 31} # add entry to a dictionary students['Fred'] = 27 # alter an entry students['Alice'] = 25 # delete entry del st

基础才是重中之重~Dictionary&lt;K,V&gt;里V的设计决定的性能

回到目录 字典对象Dictionary<K,V>我们经常会用到,而在大数据环境下,字典使用不当可能引起性能问题,严重的可能引起内在的溢出! 字典的值建议为简单类型,反正使用Tuple<T> 字典的键在查找时,时间复杂度为O(1),性能不会有任何问题,所以不要愿望它 下面代码是对500万的字典进行测试,首先赋值,然后取出一个随机机,性能在毫秒级 static void Draw() { int count = 5000000; Console.WriteLine("test

IKAnalyzer在idea配置运行出现 Main Dictionary not found!!!

下载了IKAnalyzer源码后,配置运行后出现了Main Dictionary not found!!! 异常 跟进去后发现是配置文件没有找到org/wltea/analyzer/dic/main2012.dic,查找发现idea生成的build目录中并没有main2012.dic这个文件 当我把这个文件手动放入dic目录后,运行是可以的.后来经过一顿查找,找到了一个解决方案. Project Structure -> Modules   点右边+,选择1,然后指向resource目录,选择C

[LeetCode] Longest Word in Dictionary through Deleting 删除后得到的字典中的最长单词

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographic