1、一般用法:Key和value都为基本类型
//声明和初始化
Dictionary<int,string> myDictionary=new Dictionary<int,string>();
//添加元素
myDictionary.Add(key,value);
//判断是否包含键
if(myDictionary.ContainKey(key))
//总个数
myDictionary.Count;
//遍历
foreach(string key in myDictionary.keys)
{
int resValue=myDictionary[key];
}
// 移除指定键和值
myDictionary.Remove(key);
//遍历keys和values
foreach (KeyValuePair<int,string> kvp in myDictionary)
{
string str = string.Format("key:{0} value:{1}", kvp.Key, kvp.Value);
Console.WriteLine(str);
}
Dictionary本身存储数据是成对存储的,也就是KeyValuePair,.
2、 我们在很多地方都会用到字典,他的特点就是查找很快,当然比List快。
字典必须包含名空间System.Collection.Generic
Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)
键必须是唯一的,而值不需要唯一的
键和值都可以是任何类型(比如:string, int, 自定义类型,等等)
常用属性
名称 说明
Comparer 获取用于确定字典中的键是否相等的 IEqualityComparer。
Count 获取包含在 Dictionary 中的键/值对的数目。
Item 获取或设置与指定的键相关联的值。
Keys 获取包含 Dictionary 中的键的集合。
Values 获取包含 Dictionary 中的值的集合。
常用方法
名称 说明
Add 将指定的键和值添加到字典中。
Clear 从 Dictionary 中移除所有的键和值。
ContainsKey 确定 Dictionary 是否包含指定的键。
ContainsValue 确定 Dictionary 是否包含特定值。
Equals(Object) 确定指定的 Object 是否等于当前的 Object。 (继承自 Object。)
Finalize 允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
GetEnumerator 返回循环访问 Dictionary 的枚举器。
GetHashCode 用作特定类型的哈希函数。 (继承自 Object。)
GetObjectData 实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary 实例所需的数据。
GetType 获取当前实例的 Type。 (继承自 Object。)
MemberwiseClone 创建当前 Object 的浅表副本。 (继承自 Object。)
OnDeserialization 实现 System.Runtime.Serialization.ISerializable 接口,并在完成反序列化之后引发反序列化事件。
Remove 从 Dictionary 中移除所指定的键的值。
ToString 返回表示当前对象的字符串。 (继承自 Object。)
TryGetValue 获取与指定的键相关联的值。
3、例子,当keyf为整数,values为对象
using System;
namepace SampleList
{
class Person
{
public string name;
public int age;
public Person(string name,int age)
{
this.name=name,
this.age=age
}
}
}
using System;
using System.Conllections.Genric;
namespace SampleList
{
class CustomDictionary
{
//定义一个字典变量
static Dictionary dicPerson=new Dictionary();
public static void LearnDictionaryInfo()
{
//添加键值
Person p1=new Person("hjc",22);
Person p2=new Person("tf",21);
dicPerson.Add(0,p1);
dicPerson[1]=p2;
//取值
Console.WriteLine("\n");
Console.WriteLine("取值 name:"+dicPerson[0].name+"age:"+dicPerson[0].age);
//该值
Console.WriteLine("\n");
dicPerson[1].age=20;
Console.WriteLine("取值 name:"+dicPerson[1].name+"age:"+dicPerson[1].age);
//遍历KEY
Console.WriteLine("\n");
foreach(int key in dicPerson.keys)
{
string str=string.Format("name:{0} age:{1}",dicPerson[key].name,dicPerson[key].age);
Console.WriteLine(str);
}
//遍历value
Console.WriteLine("\n");
foreach(Person p in dicPerson.Values)
{
string str=string.Formate("name:{0} age:{1}",p.name,p.age);
Console.WriteLine(str);
}