在C#中,Dictionary提供快速的基于兼职的元素查找。当你有很多元素的时候可以使用它。它包含在System.Collections.Generic名空间中。
在使用前,你必须声明它的键类型和值类型。
详细说明
必须包含名空间System.Collection.Generic
Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)
键必须是唯一的,而值不需要唯一的
键和值都可以是任何类型(比如:string, int, 自定义类型,等等)
通过一个键读取一个值的时间是接近O(1)
键值对之间的偏序可以不定义
创建和初始化一个Dictionary对象
Dictionary<int,string> myDictionary = new Dictionary<int, string="">();
添加键
C# Dictionary用法总结
1、用法1: 常规用
增加键值对之前需要判断是否存在该键,如果已经存在该键而且不判断,将抛出异常。所以这样每次都要进行判断,很麻烦,在备注里使用了一个扩展方法
public
static
void
DicSample1()
{
Dictionary<String, String> pList =
new
Dictionary<String, String>();
try
{
if
(pList.ContainsKey(
"Item1"
) ==
false
)
{
pList.Add(
"Item1"
,
"ZheJiang"
);
}
if
(pList.ContainsKey(
"Item2"
)==
false
)
{
pList.Add(
"Item2"
,
"ShangHai"
);
}
else
{
pList[
"Item2"
] =
"ShangHai"
;
}
if
(pList.ContainsKey(
"Item3"
) ==
false
)
{
pList.Add(
"Item3"
,
"BeiJiang"
);
}
}
catch
(System.Exception e)
{
Console.WriteLine(
"Error: {0}"
, e.Message);
}
//判断是否存在相应的key并显示
if
(pList.ContainsKey(
"Item1"
))
{
Console.WriteLine(
"Output: "
+ pList[
"Item1"
]);
}
//遍历Key
foreach
(var key
in
pList.Keys)
{
Console.WriteLine(
"Output Key: {0}"
, key);
}
//遍历Value
foreach
(String value
in
pList.Values)
{
Console.WriteLine(
"Output Value: {0}"
, value);
}
//遍历Key和Value
foreach
(var dic
in
pList)
{
Console.WriteLine(
"Output Key : {0}, Value : {1} "
, dic.Key, dic.Value);
}
}