using System;
using System.Collections.Generic;
namespace Dictionary泛型集合_01
{
// 学生实体类
public class Student
{
public int StuId { get; set; }
public string StuName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
// 键:学号字符串,值:学生对象
Dictionary<string, Student> stuDict = new Dictionary<string, Student>();
// 1. 添加数据
stuDict["2026001"] = new Student { StuId = 1, StuName = "张三", Age = 18 };
stuDict["2026002"] = new Student { StuId = 2, StuName = "李四", Age = 19 };
stuDict["2026003"] = new Student { StuId = 3, StuName = "王五", Age = 18 };
// 2. 安全查询学生
string searchNo = "2026002";
if (stuDict.TryGetValue(searchNo, out Student findStu))
{
Console.WriteLine($"查询结果:姓名{findStu.StuName},年龄{findStu.Age}");
}
else
{
Console.WriteLine("未找到该学生");
}
// 3. 修改学生信息
if (stuDict.ContainsKey("2026001"))
{
stuDict["2026001"].Age = 20;
Console.WriteLine($"修改后年龄:{stuDict["2026001"].Age}");
}
// 4. 遍历所有学生
Console.WriteLine("\n全部学生列表:");
foreach (var item in stuDict)
{
Console.WriteLine($"学号:{item.Key} 姓名:{item.Value.StuName} 年龄:{item.Value.Age}");
}
// 5. 删除学生
stuDict.Remove("2026003");
Console.WriteLine($"\n删除后剩余人数:{stuDict.Count}");
Console.ReadKey();
//输出结果:
//查询结果:姓名李四,年龄19
//修改后年龄:20
//全部学生列表:
//学号:2026001 姓名:张三 年龄:20
//学号:2026002 姓名:李四 年龄:19
//学号:2026003 姓名:王五 年龄:18
//删除后剩余人数:2
}
}
}