使用 C# Dictionary 字典
说明
必须包含名空间System.Collection.Generic
Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)
键必须是唯一的,而值不需要唯一的
键和值都可以是任何类型(比如:string, int, 自定义类型,等等)
通过一个键读取一个值的时间是接近O(1)
键值对之间的偏序可以不定义
使用方法:
//定义
DictionaryopenWith = new Dictionary ();
//添加元素
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
//取值
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
//更改值
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
//遍历key
foreach (string key in openWith.Keys)
{
Console.WriteLine("Key = {0}", key);
}
//遍历value
foreach (string value in openWith.Values)
{
Console.WriteLine("value = {0}", value);
}
//遍历value, Second Method
Dictionary.ValueCollection valueColl = openWith.Values;
foreach (string s in valueColl)
{
Console.WriteLine("Second Method, Value = {0}", s);
}
//遍历字典
foreach (KeyValuePairkvp in openWith)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
//添加存在的元素
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
//删除元素
openWith.Remove("doc");
if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
//判断键存在
if (openWith.ContainsKey("bmp")) // True
{
Console.WriteLine("An element with Key = \"bmp\" exists.");
}
参数为其它类型
//参数为其它类型
DictionaryOtherType = new Dictionary ();
OtherType.Add(1, "1,11,111".Split(','));
OtherType.Add(2, "2,22,222".Split(','));
Console.WriteLine(OtherType[1][2]);
参数为自定义类型
首先定义类
class DouCube
{
public int Code { get { return _Code; } set { _Code = value; } } private int _Code;
public string Page { get { return _Page; } set { _Page = value; } } private string _Page;
}
然后
//声明并添加元素
DictionaryMyType = new Dictionary ();
for (int i = 1; i <= 9; i++)
{
DouCube element = new DouCube();
element.Code = i * 100;
element.Page = "http://www.doucube.com/" + i.ToString() + ".html";
MyType.Add(i, element);
}
//遍历元素
foreach (KeyValuePairkvp in MyType)
{
Console.WriteLine("Index {0} Code:{1} Page:{2}", kvp.Key, kvp.Value.Code, kvp.Value.Page);
}
当程序用到字典时提示关键字不在字典中时说明你在创建字典的时候没有添加那个关键字
即,你的字典没有执行 Add() 放法或是执行Add()方法是没有将关键字Add进字典去:
比如:
DictionaryintDict = new Dictionary ();
string ss = intDict[0];// 当你直接这样执行后就会报 关键字不在字典中
//而像下面这样就不会.
intDict.Add(0,"Value");
string ss1 = intDict[0];
首先,看你的关键字类型是:string类型,还是自定义类型
如果是string类型,只要字典中有这个健,就一定能找到值;
但如果是自定义类型的健,
那么,请确保你这个自定义类型 实现在gethashcode()方法跟bool Equals(T obj)方法,如果没有实现这两方法,自定义类型就不能作为字典的键
static void Main()
{
Dictionary
dic.Add("1", "2");
Console.WriteLine(dic["3"]); //没有添加这样的键 ,我们就添加了“1”
}
你自己看实例