C# System.Collections.Generic.Dictionary
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的更多相关文章
- 索引超出了数组界限。 在 System.Collections.Generic.Dictionary`2.Resize
博问:Dictionary 超出了数组界限 异常: Exception type: IndexOutOfRangeException Exception message: 索引超出了数组界限. 在 S ...
- 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 ...
- 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 ...
- System.Collections.Generic的各容器类的用法
演示System.Collections.Generic的各容器类的用法. 包括:Dictionary,KeyValuePair,SortedDic tionary,SortedList,HashSe ...
- 【Azure 微服务】Service Fabric中微服务在升级时,遇见Warning - System.Collections.Generic.KeyNotFoundException 服务无法正常运行
问题描述 使用.Net Framework 4.5.2为架构的Service Fabric微服务应用,在升级后发布到Azure Fabric中,服务无法运行.通过Service Fabric Expl ...
- NHibernate无法将类型“System.Collections.Generic.IList<T>”隐式转换为“System.Collections.Generic.IList<IT>
API有一个需要实现的抽象方法: public IList<IPermission> GetPermissions(); 需要注意的是IList<IPermission>这个泛 ...
- 无法将类型为“System.Windows.Controls.SelectedItemCollection”的对象强制转换为类型“System.Collections.Generic.IList`1
在WPF中DataGrid 选择事件中获取SelectedItems 报错如下 无法将类型为“System.Windows.Controls.SelectedItemCollection”的对象强制转 ...
- Unity3d:Unknown type 'System.Collections.Generic.CollectionDebuggerView'1
问题描述:如图,在调试状态下说:Unknown type 'System.Collections.Generic.CollectionDebuggerView'1<ignore_js_op> ...
- using System.Collections.Generic;
public class CommonClass { public static void ShowInt(int iValue) { //typeof(CommonClass) typeof关键字 ...
随机推荐
- 04. Pandas 3| 数值计算与统计、合并连接去重分组透视表文件读取
1.数值计算和统计基础 常用数学.统计方法 数值计算和统计基础 基本参数:axis.skipna df.mean(axis=1,skipna=False) -->> axis=1是按行来 ...
- 063 SparkStream数据接收方式
1.两种方式 2.Basic Source 由StreamingContext可以提供的API 上面做的wordcount中的方式就算是第一种方式. 3.Advanced Source 使用数据接收器 ...
- SpringMVC-1-(简介及HelloWord)
首先我们来看一下servlet的处理请求的方式: 一:SpringMVC简介: 一)SpringMVC中的几个重要组件 1.DispatchServlet: 前端控制器,mvc模式中的c,是整个流程的 ...
- 反向传播算法(前向传播、反向传播、链式求导、引入delta)
参考链接: 一文搞懂反向传播算法
- Java常用API及Math类
一.API的概述 API——Application Programing Interface:应用程序编程接口,是java提供的一些预定义的函数: 目的:基于API实现程序的快速编写,只需了解其作用, ...
- Bi-shoe and Phi-shoe (欧拉函数)
题目描述: 题目大意:一个竹竿长度为p,它的score值就是比p长度小且与且与p互质的数字总数,比如9有1,2,4,5,7,8这六个数那它的score就是6.给你T组数据,每组n个学生,每个学生都有一 ...
- Java 之 JavaScript (一)
1.JavaScript a.定义:JavaScript 是脚本语言,是一种轻量级的编程语言 b.实现:①直接通过标签里面的onXX属性驱动js的执行 <input type="but ...
- JavaScript函数、闭包、原型、面向对象
JavaScript函数.闭包.原型.面向对象 断言 单元测试框架的核心是断言方法,通常叫assert(). 该方法通常接收一个值--需要断言的值,以及一个表示该断言目的的描述. 如果该值执行的结果为 ...
- Socket 网络通信
Socket 网络通信 1.OSI (Open System Interconnect Reference Model)(开放系统互联参考模型) 从下低到高 :物理层.数据链路层.网络层.传输层.会话 ...
- LOJ.6073.[2017山东一轮集训Day5]距离(可持久化线段树 树链剖分)
题目链接 就是恶心人的,简单写写了...(似乎就是[HNOI2015]开店?) 拆式子,记\(dis_i\)为\(i\)到根节点的路径权值和,\(Ans=\sum dis_{p_i}+\sum dis ...