C# System.Collections.Generic.Dictionary

时间:2022-02-13 06:41:28
 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)

获取与指定键关联的值。