using System;
using System.Collections.Generic; public class Example
{
public static void Main()
{
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
new Dictionary<string, string>(); // Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe"); // The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
} // The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]); // The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]); // If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe"; // The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
Console.WriteLine("For key = \"tif\", value = {0}.",
openWith["tif"]);
}
catch (KeyNotFoundException)
{
Console.WriteLine("Key = \"tif\" is not found.");
} // When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
Console.WriteLine("Key = \"tif\" is not found.");
} // ContainsKey can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}",
openWith["ht"]);
} // When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
} // To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
openWith.Values; // The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in valueColl )
{
Console.WriteLine("Value = {0}", s);
} // To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
openWith.Keys; // The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
Console.WriteLine("Key = {0}", s);
} // Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc"); if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
}
} /* This code example produces the following output: An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht Remove("doc")
Key "doc" is not found.
*/
 using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
//一、创建泛型哈希表,然后加入元素
Dictionary<string, string> oscar = new Dictionary<string, string>();
oscar.Add("哈莉?贝瑞", "《死囚之舞》");
oscar.Add("朱迪?丹奇", "《携手人生》");
oscar.Add("尼科尔?基德曼", "《红磨坊》");
oscar.Add("詹妮弗?康纳利", "《美丽心灵》");
oscar.Add("蕾妮?齐维格", "《BJ单身日记》"); //二、删除元素
oscar.Remove("詹妮弗?康纳利"); //三、假如不存在元素则加入元素
if (!oscar.ContainsKey("茜茜?斯派克")) oscar.Add("茜茜?斯派克", "《不伦之恋》"); //四、显然容量和元素个数
Console.WriteLine("元素个数: {0}", oscar.Count); //五、遍历集合
Console.WriteLine("74届奥斯卡最佳女主角及其电影:");
foreach (KeyValuePair<string, string> kvp in oscar)
{
Console.WriteLine("姓名:{0},电影:{1}", kvp.Key, kvp.Value);
} //六、得到哈希表中键的集合
Dictionary<string, string>.KeyCollection keyColl = oscar.Keys;
//遍历键的集合
Console.WriteLine("最佳女主角:");
foreach (string s in keyColl)
{
Console.WriteLine(s);
} //七、得到哈希表值的集合
Dictionary<string, string>.ValueCollection valueColl = oscar.Values;
//遍历值的集合
Console.WriteLine("最佳女主角电影:");
foreach (string s in valueColl)
{
Console.WriteLine(s);
} //八、使用TryGetValue方法获取指定键对应的值
string slove = string.Empty;
if (oscar.TryGetValue("朱迪?丹奇", out slove))
Console.WriteLine("我最喜欢朱迪?丹奇的电影{0}", slove);
else
Console.WriteLine("没找到朱迪?丹奇的电影"); //九、清空哈希表
oscar.Clear();
Console.ReadLine();
}
}
 //定义字典
Dictionary<string, string> d = new Dictionary<string, string>(); //添加字典的元素
for (int i = ; i < ; i++)
{
d.Add("key" + i, "value" + i);
} //取值/赋值
string val = d["key1"];
d["key1"] = "new value"; //遍历key
foreach (string key in d.Keys)
{
Console.WriteLine("Key = {0}", key);
}
//遍历value
foreach (string v in d.Values)
{
Console.WriteLine("value = {0}", v);
} //遍历value, Second Method
Dictionary<string, string>.ValueCollection valueColl = d.Values;
foreach (string s in valueColl)
{
Console.WriteLine("Second Method, Value = {0}", s);
} //遍历字典
foreach (KeyValuePair<string, string> kvp in d)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
//删除元素
d.Remove("key1");
if (!d.ContainsKey("key1"))
{
Console.WriteLine("Key \"key1\" is not found.");
}
//判断键存在
if (d.ContainsKey("key1")) // True
{
Console.WriteLine("An element with Key = \"key1\" exists.");
}

构造函数

Dictionary<TKey,TValue>()

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有默认的初始容量,并使用键类型的默认相等比较器。

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并为键类型使用默认的相等比较器。

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并使用指定的 IEqualityComparer<T>

Dictionary<TKey,TValue>(IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有默认的初始容量,并使用指定的 IEqualityComparer<T>

Dictionary<TKey,TValue>(Int32)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有指定的初始容量,并为键类型使用默认的相等比较器。

Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有指定的初始容量,并使用指定的 IEqualityComparer<T>

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

用序列化数据初始化 Dictionary<TKey,TValue> 类的新实例。

属性

Comparer

获取用于确定字典中的键是否相等的 IEqualityComparer<T>

Count

获取包含在 Dictionary<TKey,TValue> 中的键/值对的数目。

Item[TKey]

获取或设置与指定的键关联的值。

Keys

获取包含 Dictionary<TKey,TValue> 中的键的集合。

Values

获取包含 Dictionary<TKey,TValue> 中的值的集合。

方法

Add(TKey, TValue)

将指定的键和值添加到字典中。

Clear()

将所有键和值从 Dictionary<TKey,TValue> 中移除。

ContainsKey(TKey)

确定是否 Dictionary<TKey,TValue> 包含指定键。

ContainsValue(TValue)

确定 Dictionary<TKey,TValue> 是否包含特定值。

Equals(Object)

确定指定的对象是否等于当前对象。

(Inherited from Object)

GetEnumerator()

返回循环访问 Dictionary<TKey,TValue> 的枚举数。

GetHashCode()

作为默认哈希函数。

(Inherited from Object)

GetObjectData(SerializationInfo, StreamingContext)

实现 ISerializable 接口,并返回序列化 Dictionary<TKey,TValue> 实例所需的数据。

GetType()

获取当前实例的 Type

(Inherited from Object)

MemberwiseClone()

创建当前 Object 的浅表副本。

(Inherited from Object)

OnDeserialization(Object)

实现 ISerializable 接口,并在完成反序列化之后引发反序列化事件。

Remove(TKey)

从 Dictionary<TKey,TValue> 中移除所指定的键的值。

ToString()

返回表示当前对象的字符串。

(Inherited from Object)

TryGetValue(TKey, TValue)

获取与指定键关联的值。

C# System.Collections.Generic.Dictionary的更多相关文章

  1. 索引超出了数组界限。 在 System.Collections.Generic.Dictionary`2.Resize

    博问:Dictionary 超出了数组界限 异常: Exception type: IndexOutOfRangeException Exception message: 索引超出了数组界限. 在 S ...

  2. Web api help page error CS0012: Type "System.Collections.Generic.Dictionary'2错误

    1.在asp.net Boilerplate项目中,Abp.0.12.0.2,.net framework4.5.2.下载后添加了webApi的helpPage功能,调试出现错误. dubug : a ...

  3. System.ArgumentException: 已添加了具有相同键的项。(An item with the same key has already been added) 在 System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) 在 System.Web.Mvc.Js

    最近将一个项目从ASP.NET MVC 3升级至刚刚发布的ASP.NET MVC 5.1,升级后发现一个ajax请求出现了500错误,日志中记录的详细异常信息如下: System.ArgumentEx ...

  4. System.Collections.Generic的各容器类的用法

    演示System.Collections.Generic的各容器类的用法. 包括:Dictionary,KeyValuePair,SortedDic tionary,SortedList,HashSe ...

  5. 【Azure 微服务】Service Fabric中微服务在升级时,遇见Warning - System.Collections.Generic.KeyNotFoundException 服务无法正常运行

    问题描述 使用.Net Framework 4.5.2为架构的Service Fabric微服务应用,在升级后发布到Azure Fabric中,服务无法运行.通过Service Fabric Expl ...

  6. NHibernate无法将类型“System.Collections.Generic.IList<T>”隐式转换为“System.Collections.Generic.IList<IT>

    API有一个需要实现的抽象方法: public IList<IPermission> GetPermissions(); 需要注意的是IList<IPermission>这个泛 ...

  7. 无法将类型为“System.Windows.Controls.SelectedItemCollection”的对象强制转换为类型“System.Collections.Generic.IList`1

    在WPF中DataGrid 选择事件中获取SelectedItems 报错如下 无法将类型为“System.Windows.Controls.SelectedItemCollection”的对象强制转 ...

  8. Unity3d:Unknown type 'System.Collections.Generic.CollectionDebuggerView'1

    问题描述:如图,在调试状态下说:Unknown type 'System.Collections.Generic.CollectionDebuggerView'1<ignore_js_op> ...

  9. using System.Collections.Generic;

    public class CommonClass { public static void ShowInt(int iValue) { //typeof(CommonClass) typeof关键字 ...

随机推荐

  1. utf-8和utf8的区别

    utf-8 和 utf8 的区别与使用: "UTF-8" 是标准写法,php 在 Windows 系统里的英文不区分大小写,所以也可以写成 "utf-8".&q ...

  2. python 精确计算与向上取整 decimal math.ceil

    1. 精确计算 python的float型不精确,需要导入decimal包,以下是不精确举例: 导入decimal包后: 2. 向上取整 一般的取整数(向下取整): 向上取整的方法:

  3. oracle中

    select tmp_tb.*, ROWNUM row_id from (SELECT MX.*                                          --这里不能直接用* ...

  4. Hexo博客yilia主题添加Gitment评论系统

    一开始搭建hexo+yilia博客使用的评论功能是通过来必力实现的.来必力免费,功能多,一开始的体验效果很好,但是后来打开网站发现来必力加载的越来越慢(来必力是韩国的公司,可能是国内限制),遂打算换一 ...

  5. Codeforces 1131F Asya And Kittens (构造)【并查集】

    <题目链接> 题目大意:有$n$只小猫,开始将它们放在指定的n个单元格内,然后随机从n-1个隔板中拆除隔板,最终使得这些小猫在同一单元格.现在依次给出拆除隔板的顺序,比如:1 4 就表示1 ...

  6. pymysql:Mysql拒绝从远程访问的解决办法

    pymysql:Mysql拒绝从远程访问的解决办法 pymysql连接数据库 # 导入pymysql模块 import pymysql # 连接database conn = pymysql.conn ...

  7. .NET SQL优化

    1.没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) 2.I/O吞吐量小,形成了瓶颈效应. 3.没有创建计算列导致查询不优化. 4.内存不足 5.网络速度慢 6.查询出的数据量过大 ...

  8. Xamarin Essentials教程陀螺仪Gyroscope

    Xamarin Essentials教程陀螺仪Gyroscope   陀螺仪是用来检测设备在X.Y.Z轴上所旋转的角速度.应用程序通过陀螺仪可以获取设备在各个方向的转动角速度,可以实现更为丰富的控制功 ...

  9. Java基础巩固——《Java核心技术基础·卷一:基础知识》

    阅读记录追踪:前言部分 阅读前先看:简介.目录和勘误! Java编程语言是一种多用途.并发的.基于类的.面向对象的编程语言:编译时通常包括将持续转化成机器无关的字节码表示.运行时活动包括加载和链接执行 ...

  10. CC2431 代码分析④-衣锦还乡的CC2431

    我们在第二节就分析到了 finishCollection( void ),但是当我们分析完第三节后,整个系统才真正执行到这里,我们依然像第二节一样把这个函数全部贴出来 /*************** ...