From 5f29bb80c72702eb19b45d356d67afbdf7104a58 Mon Sep 17 00:00:00 2001 From: Amen-under-Wu <79252921+Amen-under-Wu@users.noreply.github.com> Date: Mon, 4 Aug 2025 19:15:42 +0800 Subject: [PATCH] feat: homework required --- Homework/Program.cs | 198 +++++++++++++++++++++++++++++++------------- 1 file changed, 139 insertions(+), 59 deletions(-) diff --git a/Homework/Program.cs b/Homework/Program.cs index b728a41..0915c7e 100644 --- a/Homework/Program.cs +++ b/Homework/Program.cs @@ -1,4 +1,4 @@ -// See https://aka.ms/new-console-template for more information +// See https://aka.ms/new-console-template for more information using System; using System.Collections.Generic; using System.IO; @@ -9,17 +9,21 @@ namespace StudentManagementSystem public enum Grade { // TODO: 定义成绩等级 F(0), D(60), C(70), B(80), A(90) - + F = 0, + D = 60, + C = 70, + B = 80, + A = 90, } // 泛型仓储接口 public interface IRepository { // TODO: 定义接口方法 - // Add(T item) - // Remove(T item) 返回bool - // GetAll() 返回List - // Find(Func predicate) 返回List + public void Add(T item); + public bool Remove(T item); + public List GetAll(); + List Find(Func predicate); } @@ -27,25 +31,29 @@ public interface IRepository public class Student : IComparable { // TODO: 定义字段 StudentId, Name, Age - - + public readonly string StudentId; + public readonly string Name; + public readonly int Age; + public Student(string studentId, string name, int age) { - // TODO: 实现构造方法,包含参数验证(空值检查) - + if ((studentId is null) || (name is null)) + { + throw new ArgumentException("Null Parameter"); + } + StudentId = studentId; + Name = name; + Age = age; } public override string ToString() { - // TODO: 返回格式化的学生信息字符串 - + return $$"""Student { StudentId : {{StudentId}}, Name : {{Name}}, Age : {{Age}} }"""; } - // TODO: 实现IComparable接口,按学号排序 - // 提示:使用string.Compare方法 public int CompareTo(Student? other) { - + return String.Compare(StudentId, other?.StudentId); } public override bool Equals(object? obj) @@ -62,19 +70,22 @@ public override int GetHashCode() // 成绩类 public class Score { - // TODO: 定义字段 Subject, Points - + public readonly string Subject; + public readonly double Points; public Score(string subject, double points) { - // TODO: 实现构造方法,包含参数验证 - + if (subject is null) + { + throw new ArgumentException("Null Parameter"); + } + Subject = subject; + Points = points; } public override string ToString() { - // TODO: 返回格式化的成绩信息 - + return $$"""Score { Subject : {{Subject}}, Points : {{Points}} }"""; } } @@ -83,39 +94,43 @@ public class StudentManager : IRepository { // TODO: 定义私有字段存储学生列表 // 提示:使用List存储 - + private List Students = new List(); public void Add(Student item) { - // TODO: 实现添加学生的逻辑 - // 1. 参数验证 - // 2. 添加到列表 - + if (item is not null) + { + Students.Add(item); + } } public bool Remove(Student item) { - // TODO: 实现Remove方法 - + return Students.Remove(item); } public List GetAll() { - // TODO: 返回学生列表的副本 - + return new List(Students); } public List Find(Func predicate) { - // TODO: 使用foreach循环查找符合条件的学生 - + var res = new List(); + foreach (var item in Students) + { + if (predicate(item)) + { + res.Add(item); + } + } + return res; } // 查找年龄在指定范围内的学生 public List GetStudentsByAge(int minAge, int maxAge) { - // TODO: 使用foreach循环和if判断实现年龄范围查询 - + return this.Find(student => student.Age <= maxAge && student.Age >= minAge); } } @@ -124,46 +139,63 @@ public class ScoreManager { // TODO: 定义私有字段存储成绩字典 // 提示:使用Dictionary>存储 - + private Dictionary> ScoreDict = new Dictionary>(); public void AddScore(string studentId, Score score) { - // TODO: 实现添加成绩的逻辑 - // 1. 参数验证 - // 2. 初始化学生成绩列表(如不存在) - // 3. 添加成绩 - + if (studentId is not null) + { + if (! ScoreDict.ContainsKey(studentId)) + { + ScoreDict.Add(studentId, new List()); + } + ScoreDict[studentId].Add(score); + } } public List GetStudentScores(string studentId) { - // TODO: 获取指定学生的所有成绩 - + return ScoreDict[studentId]; } public double CalculateAverage(string studentId) { - // TODO: 计算指定学生的平均分 - // 提示:使用foreach循环计算总分,然后除以科目数 - + double res = 0; + var l = ScoreDict[studentId]; + foreach (var score in l) + { + res += score.Points; + } + return res / l.Count(); } - // TODO: 使用模式匹配实现成绩等级转换 public Grade GetGrade(double score) { - + return score switch + { + < 60 => Grade.F, + >= 60 and < 70 => Grade.D, + >= 70 and < 80 => Grade.C, + >= 80 and < 90 => Grade.B, + >= 90 => Grade.A, + _ => throw new ArgumentOutOfRangeException("Invalid score value") + }; } public List<(string StudentId, double Average)> GetTopStudents(int count) { - // TODO: 使用简单循环获取平均分最高的学生 - // 提示:可以先计算所有学生的平均分,然后排序取前count个 - + var res = new List<(string StudentId, double Average)>(); + foreach (var item in ScoreDict) + { + res.Add((item.Key, CalculateAverage(item.Key))); + } + res.Sort((x, y) => -x.Item2.CompareTo(y.Item2)); + return res.GetRange(0, count); } public Dictionary> GetAllScores() { - return new Dictionary>(scores); + return new Dictionary>(ScoreDict); } } @@ -177,7 +209,14 @@ public void SaveStudentsToFile(List students, string filePath) try { // 在这里实现文件写入逻辑 - + using (StreamWriter writer = new StreamWriter(filePath)) + { + writer.WriteLine("StudentId,Name,Age"); + foreach (var student in students) + { + writer.WriteLine($"{student.StudentId},{student.Name},{student.Age}"); + } + } } catch (Exception ex) { @@ -193,8 +232,24 @@ public List LoadStudentsFromFile(string filePath) // 提示:使用StreamReader,解析CSV格式 try { - // 在这里实现文件读取逻辑 - + using (StreamReader reader = new StreamReader(filePath)) + { + string line; + // 跳过标题行 + reader.ReadLine(); + + while ((line = reader.ReadLine()) != null) + { + var parts = line.Split(','); + if (parts.Length == 3) + { + string studentId = parts[0].Trim(); + string name = parts[1].Trim(); + int age = int.Parse(parts[2].Trim()); + students.Add(new Student(studentId, name, age)); + } + } + } } catch (Exception ex) { @@ -241,21 +296,46 @@ static void Main(string[] args) // 3. 测试年龄范围查询 Console.WriteLine("\n3. 查找年龄在19-20岁的学生:"); // TODO: 调用GetStudentsByAge方法并显示结果 - + var students_temp = studentManager.GetStudentsByAge(19, 20); + foreach (var student in students_temp) + { + Console.WriteLine(student); + } // 4. 显示学生成绩统计 Console.WriteLine("\n4. 学生成绩统计:"); - // TODO: 遍历所有学生,显示其成绩、平均分和等级 + foreach (var student in studentManager.GetAll()) + { + var scores = scoreManager.GetStudentScores(student.StudentId); + Console.WriteLine($"{student.Name} 的成绩:"); + foreach (var score in scores) + { + Console.WriteLine($"科目: {score.Subject}, 分数: {score.Points}, 等级: {scoreManager.GetGrade(score.Points)}"); + } + double average = scoreManager.CalculateAverage(student.StudentId); + Console.WriteLine($"平均分: {average}, 等级: {scoreManager.GetGrade(average)}\n"); + } // 5. 显示排名(简化版) Console.WriteLine("\n5. 平均分最高的学生:"); - // TODO: 调用GetTopStudents(1)方法显示第一名 + Console.WriteLine(scoreManager.GetTopStudents(1)[0].StudentId); // 6. 文件操作 Console.WriteLine("\n6. 数据持久化演示:"); - // TODO: 保存和读取学生文件 + string filePath = "students.csv"; + // 保存学生数据到文件 + dataManager.SaveStudentsToFile(studentManager.GetAll(), filePath); + Console.WriteLine($"学生数据已保存到 {filePath}"); + + // 从文件加载学生数据 + var loadedStudents = dataManager.LoadStudentsFromFile(filePath); + Console.WriteLine("从文件加载的学生数据:"); + foreach (var student in loadedStudents) + { + Console.WriteLine(student); + } } @@ -268,4 +348,4 @@ static void Main(string[] args) Console.ReadKey(); } } -} \ No newline at end of file +}