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. P1026 统计单词个数 区间dp

    题目描述 给出一个长度不超过200200的由小写英文字母组成的字母串(约定;该字串以每行2020个字母的方式输入,且保证每行一定为2020个).要求将此字母串分成kk份(1<k \le 401& ...

  2. 012 pandas与matplotlib结合制图

    这里以后再补充. 1.折线图

  3. mybatis的xml处理大于和小于号问题

    https://blog.csdn.net/u022812849/article/details/42123007

  4. HDU 5592 ZYB's Game 【树状数组】+【二分】

    <题目链接> 题目大意: 给你一个由1~n,n个数组成的序列,给出他们每个的前缀逆序数,现在要求输出这个序列. 解题分析: 由前缀逆序数很容易能够得到每个数的逆序数.假设当前数是i,它前面 ...

  5. 3-6 Vue中的条件渲染

    本次案例讲解:v-if,v-show,v-else,v-else-if和key值的相关用法!!! v-if指令: //通过一个(v-if)指令 ,可以结合js表达式的返回值,决定一个标签是否在页面上展 ...

  6. Qt创建任务栏进度条

    一.正文 任务栏进度条是Windows7就引入的一种UI形式,通常用于显示软件当前正在执行的任务的进度(如编译程序的进度.下载任务的进度).如下: 在Qt中使用任务栏进度条也是非常容易的一件事情.Qt ...

  7. linux 学习笔记 APACHE安装总结

    #cd /usr/local #mkdir APACHE #tar zxvf /usr/etc/DEV/httpd-2.2.9.tar.gz #mv httpd-2.2.9/* . #rm -rf h ...

  8. 谈谈《Dotnet core结合jquery的前后端加密解密密码密文传输的实现》一文中后端解密失败的原因

    详情请看<Dotnet core结合jquery的前后端加密解密密码密文传输的实现>,正常来讲,这个博客里面的代码是没有问题的,但是我有时候却会直接报错,原因是后台解密失败:Interna ...

  9. [PA2014]Zadanie

    [PA2014]Zadanie 题目大意: 一棵\(n(n\le3\times10^5)\)个点的树,每个点上有\(a_i\)个人.树上所有人到\(i\)号点距离之和为\(b_i\).已知\(\{b_ ...

  10. [P3369]普通平衡树(Splay版)

    模板,不解释 #include<bits/stdc++.h> using namespace std; const int mxn=1e5+5; int fa[mxn],ch[mxn][2 ...