.NET C# Web开发学习之路(11)—— Dictionary 字典
Dictionary概述
- 必须包含命名空间System.Collection.Generic
- Dictionary里面的每一个元素都是一个键值对(由两个元组组成:键和值).
- 键必须是唯一的,而值不需要唯一的.
- 键和值都可以是任意类型(例如:string,int,自定义类型,等等)
- 通过一个键读取一个值的事件是接近O(1)
- 键值对之间的偏序可以不定义
创建一个Dictionary对象的语法格式如下:
Dictionary<type1,type2> dicName = new Dictionary<type1,type2>();
说明:
- type1:键的数据类型,不能为空
- type2:值的数据类型,可以为空
- dicName:字典对象的名称
Dictionary使用
1、定义
Dictionary<string,string> Dic = new Dictionary<string,string>();
2、添加元素
Dic.Add("Name","James");
Dic.Add("Age","Fouty");
Dic.Add("Sex","Man");
Dic.Add("Position","Player");
3、取值
Console.WriteLine("Key:Name,Value:{1}",Dic["Name"]);
4、更改值
Dic["Name"] = "Bob";
Console.WriteLine("Key:Name,Value:{1}",Dic["Name"]);
5、遍历Key
foreach(string key in Dic.Keys)
{
Console.WriteLine("Key ={0}",key);
}
6、遍历值
//One
foreach(string value in Dic.Values)
{
Console.WriteLine("value = {0}",value);
}
//two
Dictionary<string,string>.ValueCollection valueColl = Dic.Values;
foreach(string s in valueColl)
{
Console.WriteLine("value = {0}",s);
}
7、遍历字典
foreach(KeyValuePair<string,string> kvp in Dic)
{
Console.WriteLine("Key = {0},Value = {1}",kvp.key,kvp.value);
}
8、删除元素
Dic.Remove("Score");
if(!Dic.ContainsKey("Score"))
{
Console.WriteLine("Key Score is not Found");
}
Dictionary常用属性和说明
属性 | 说明 |
---|---|
Comparer | 获取用于确定字典中是否相等的IEqualityComparer<T> |
Count | 获取包含在Dictionary中的键/值对数目 |
Item | 获取或设置与指定的键相关的值 |
Keys | 获取包含Dictionary中的键的集合 |
Values | 获取包含Dictionary中的值的集合 |