在C#中,Dictionary的主要用途是提供快速的基于键值的元素查找。Dictionary的结构一般是这样的:Dictionary<[key], [value]> ,它包含在System.Collections.Generic命名空间中。在使用Dictionary前,你必须对它的键类型和值类型进行声明。
Dictionary的描述
- 从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
- 任何键都必须是唯一的
- 键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值
- Key和Value可以是任何类型(string,int,custom class 等)
类的对象作为Value,对字典Dictionary进行创建及初始化
第一步:建立一个Student类
class Student
{
private int age;
public string StuName { get; set; }
public int StuId { get; set; }
public int Age
{
get => age;
set => age = (value < 18) ? 18 : value;
}
public Student() { StuName = "xiexie"; StuId = 1117; Age = 23; }
public Student(string str, int a, int i) { StuName = str; StuId = i; Age = a; }
public string StuShow()
{
string info = String.Format("姓名:{0},年龄:{1},学号:{2}", StuName, Age, StuId);
return info;
}
}
字典的创建和初始化
//创建类的对象
Student stu1 = new Student("Jack", 15, 1001);
Student stu2 = new Student("Tom", 22, 1002);
Student stu3 = new Student("Lucy", 35, 1003);
Student stu4 = new Student("Eric", 8, 1004);
Dictionary<string, Student> stuDict = new Dictionary<string, Student>();
stuDict.Add("Jack", stu1); //<key, Value>
stuDict.Add("Tom", stu2);
stuDict.Add("Lucy", stu3);
stuDict.Add("Eric", stu4);
通过字典的Key查考字典的内容:
Console.WriteLine(stuDict["Tom"].StuShow());
两种遍历方式:
//通过遍历Key,再通过字典中的对象调用对象的方法
foreach (string key in stuDict.Keys)
{
Console.WriteLine(key);
Console.WriteLine(stuDict[key].StuShow());
}
//通过遍历Value,直接调用对象方法
foreach (var value in stuDict.Values)
{
Console.WriteLine(value.StuShow());
}
其他
其它常见属性和方法的说明:
Comparer: 获取用于确定字典中的键是否相等的 IEqualityComparer。
Count: 获取包含在 Dictionary中的键/值对的数目。
Item: 获取或设置与指定的键相关联的值。
Keys: 获取包含 Dictionary中的键的集合。
Values: 获取包含 Dictionary中的值的集合。
Add: 将指定的键和值添加到字典中。
Clear: 从 Dictionary中移除所有的键和值。
ContainsKey: 确定 Dictionary是否包含指定的键。
ContainsValue: 确定 Dictionary是否包含特定值。
GetEnumerator: 返回循环访问 Dictionary的枚举数。
GetType: 获取当前实例的 Type。 (从 Object 继承。)
Remove: 从 Dictionary中移除所指定的键的值。
ToString: 返回表示当前 Object的 String。 (从 Object 继承。)
TryGetValue: 获取与指定的键相关联的值。