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关键字 ...
随机推荐
- 解析eBay BASE模式、去哪儿及蘑菇街分布式架构
目录:问题分析概念解读Most Simple原理解读eBey.去哪儿.蘑菇街分布式事务案例分析 参考资料 1.问题解析 要想做架构,必须识别出问题,即是谁的问题,什么问题.明显的,分布式架构解决 ...
- Python中元类
元类(metaclass) 简单地说,元类就是一个能创建类的类,而类class 是由type创建的,class可以创建对象 type与object的关系详见:python中type和object 1. ...
- Create-react-app+Antd-mobile+Less配置(学习中的记录)
(参考别人结合自己的整理得出,若有错误请大神指出) Facebook 官方推出Create-React-App脚手架,基本可以零配置搭建基于webpack的React开发环境,内置了热更新等功能. 详 ...
- python和yum同时卸载后的安装方法
centos 7如果卸载了yum和python之后恢复的办法(该方法已经测试). 1. 安装python. python-libs-2.7.5-34.el7.x86_64.rpm python-2.7 ...
- 【未解决】Linux下PHP安装扩展Mysql的问题
[步骤分析] 1.在PHP源码包下定位到指定位置:源码包/ext/mysqli 注1:网上很多地方红字部分是mysql,其实PHP5以后已经不用mysql了. 2.运行:/usr/local/php/ ...
- RESTful架构&简单使用Django rest framework
RESTful架构 1 什么是REST REST全称是Representational State Transfer,中文意思是表述性状态转移. 它首次出现在2000年Roy Fielding的博士论 ...
- ReentrantLock和condition源码浅析(二)
转载请注明出处... 接着上一篇的ReentrantLock和condition源码浅析(一),这篇围绕着condition 一.condition的介绍 在这里为了作对比,引入Object类的两个方 ...
- EF Core中Fluent Api如何删除指定数据表中的行
这两天一直在研究在code first下如何删除数据表中的指定行,于是开始搜狗,后来百度,压根就找不到资料,后来一想可能我的搜索关键字有问题,而且ef core命令与ef的命令差不多,于是从这两个方面 ...
- SpringBoot应用War包形式部署到外部Tomcat
这一篇文章介绍SpringBoot应用修改默认打jar形式部署为打war包形式,部署到外部Tomcat. SpringBoot应用默认打包成为可执行jar模式让我们感觉到部署的便捷,接下来给大家介绍一 ...
- BZOJ.4559.[JLOI2016]成绩比较(DP/容斥 拉格朗日插值)
BZOJ 洛谷 为什么已经9点了...我写了多久... 求方案数,考虑DP... \(f[i][j]\)表示到第\(i\)门课,还有\(j\)人会被碾压的方案数. 那么\[f[i][j]=\sum_{ ...