字典
处理和表现类似key-value的键值对的集合
key和value的类型由泛型指定
key值必须唯一,区分大小写
value可以是值类型变量,也可以是对象
using System;
using System.Collections.Generic;namespace dDic
{
class Student {
public string number;
public string name;public Student(string number, string name)
{
this.number = number;
this.name = name;
}
public override string ToString()
{
return $"学生:{number},{name}";
}
}
class Program
{
static void Main(string[] args)
{
//字典实例化
Dictionary<string, Student> students = new Dictionary<string, Student>();
students.Add("200101", new Student("200101", "xiaoming"));
students.Add("200102", new Student("200102", "xiaohong"));
students.Add("200103", new Student("200103", "xiaowang"));
//删除
students.Remove("200103");
//判断是否包含某个key
bool costainsKey = students.ContainsKey("200109");
Console.WriteLine("containsKey:" + costainsKey);
//查看
Console.WriteLine("students[\"200102\"]:" + students["200102"]);
bool containsValue = students.ContainsValue(new Student("200101","xiaoming"));
Console.WriteLine("containsValue:" + containsValue);
//遍历字典
foreach (var item in students) {
Console.WriteLine("item.Key:" + item.Key);
Console.WriteLine("item.Value:" + item.Value);
}
//遍历所有Key
foreach (var item in students.Keys) {
Console.WriteLine(item);
}
//遍历所有value
foreach (var item in students.Values) {
Console.WriteLine(item);
}
//TryGetValue:尝试获取某个值
Student tempStudent;
bool getSuccess = students.TryGetValue("200101",out tempStudent);
Console.WriteLine("getSuccuss:"+getSuccess);
if (getSuccess)
{
Console.WriteLine(tempStudent);
}
else {
Console.WriteLine("tempStudent == null"+tempStudent == null);
}}
}
}