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

Dictionary使用(转)的更多相关文章

  1. C#数组,List,Dictionary的相互转换

    本篇文章会向大家实例讲述以下内容: 将数组转换为List 将List转换为数组 将数组转换为Dictionary 将Dictionary 转换为数组 将List转换为Dictionary 将Dicti ...

  2. ASP.NET Aries JSAPI 文档说明:AR.DataGrid、AR.Dictionary

    AR.Global 文档 1:对象或属性: 名称 类型 说明 DG 对象 DataGrid操作对象 //datagrid集合,根据ID取出DataGrid对象,将Json当数组用. Items: ne ...

  3. WebAPI接口返回ArrayList包含Dictionary对象正确解析

    一.问题提出 为了减少流量,将key-value(键值对)直接输出到Dictionary<string, string>,接口返回结果如下: 其中{}里面内容如下: 上图显示600是键,4 ...

  4. Linq在Array,List,Dictionary中的应用

    Linq在Array,List,Dictionary中的应用 今天在实际工作中需要对array,list,dictionary进行排序,试一试linq,发现非常好用,代码如下: using Syste ...

  5. python之最强王者(8)——字典(dictionary)

    1.Python 字典(Dictionary) 字典是另一种可变容器模型,且可存储任意类型对象. 字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包 ...

  6. Swift3 - String 字符串、Array 数组、Dictionary 字典的使用

    Swift相关知识,本随笔为 字符串.数组.字典的简单使用,有理解.使用错误的地方望能指正. ///************************************************** ...

  7. [LeetCode] Alien Dictionary 另类字典

    There is a new alien language which uses the latin alphabet. However, the order among letters are un ...

  8. Dictionary

    命名空间:System.Collections.Generic(程序集:mscorlib) Dictionary<TKey, TValue> 类   一般用法:通过key获取value,k ...

  9. 关于 Dictionary<string,string>,和List<T>在View的使用

    在MVC中Dictionary<string,string>如何应用到View页面中呢,例: <input type="text" name=key value= ...

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

    第一部分 字典学习以及稀疏表示的概要 字典学习(Dictionary Learning)和稀疏表示(Sparse Representation)在学术界的正式称谓应该是稀疏字典学习(Sparse Di ...

随机推荐

  1. parseInt(),parseFloat(),parse()

    1.parseInt() 该函数将变量转换为整型数.只有对字符串型的数据调用该函数才有意义,其他类型如果使用parseInt()函数,则会返回NaN. 2.parseFloat() 该函数和parse ...

  2. byte[]和InputStream的相互转换

    1:byte[]转换为InputStream InputStream sbs = new ByteArrayInputStream(byte[] buf); 2:InputStream转换为Input ...

  3. UIImageView动画

    NSMutableArray *arrM = [NSMutableArray array]; // 2.加载所有图片 ; i <= ; i++) { NSString *imageName = ...

  4. js document

    <html><head lang="en"> <meta charset="UTF-8"> <title>< ...

  5. centos 安装FTP server详情(转)

    centos 安装FTP server详情 分类: linux 2013-12-27 16:45 227人阅读 评论(0) 收藏 举报 我们这里以安装vsftpd 服务器端为例子: 1.进入到cent ...

  6. ural1890 Money out of Thin Air

    Money out of Thin Air Time limit: 1.0 secondMemory limit: 64 MB Each employee of the company Oceanic ...

  7. CodeForces 614D Skills

    排序+枚举+二分 最大的那些变成A,小的那部分提高最小值 #include<cstdio> #include<cstring> #include<cmath> #i ...

  8. word采用尾注进行参考文献排版的一些问题

    使用Word中尾注的功能可以很好地解决论文中参考文献的排序问题.方法如下: 1.光标移到要插入参考文献的地方,菜单中“插入”——“引用”——“脚注和尾注”. 2.对话框中选择“尾注”,编号方式选“自动 ...

  9. hibernate--多对多单向关联 (重点!!!)

    老师和学生的关系, 一个老师对多个学生, 一个学生也对应多个老师. 数据库会需要3个表, 一个老师表, 一个学生表, 一个老师对应学生表. 单向: 老师知道自己有多少学生, 但是学生不知道自己有多少个 ...

  10. MySQL的mysql_insert_id和LAST_INSERT_ID

    摘要:mysql_insert_id和LAST_INSERT_ID二者作用一样,均是返回最后插入值的ID 值 1 mysql_insert_id 一.PHP获取MYSQL新插入数据的ID  mysql ...