diff --git a/Homework/Program.cs b/Homework/Program.cs index b728a41..b2b3f4c 100644 --- a/Homework/Program.cs +++ b/Homework/Program.cs @@ -1,7 +1,9 @@ // See https://aka.ms/new-console-template for more information using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; +using System.Xml.Linq; namespace StudentManagementSystem { @@ -9,17 +11,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 + void Add(T item); + bool Remove(T item); + List GetAll(); + List Find(Func predicate); } @@ -27,25 +33,37 @@ 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 (string.IsNullOrEmpty(studentId)) + throw new ArgumentNullException("学号不能为空"); + if (string.IsNullOrWhiteSpace(name)) + throw new ArgumentException("姓名不能为空"); + if (age <= 0) + throw new ArgumentException("年龄不能为空"); + + StudentId = studentId; + Name = name; + Age = age; } public override string ToString() { // TODO: 返回格式化的学生信息字符串 - + return $"学号: {StudentId}, 姓名: {Name}, 年龄: {Age}"; } // TODO: 实现IComparable接口,按学号排序 // 提示:使用string.Compare方法 public int CompareTo(Student? other) { - + if (other == null) return 1; + return string.Compare(StudentId, other.StudentId, StringComparison.Ordinal); } public override bool Equals(object? obj) @@ -63,18 +81,27 @@ 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: 实现构造方法,包含参数验证 - + Subject = subject; + Points = points; + + if (string.IsNullOrWhiteSpace(subject)) + throw new ArgumentException("科目不能为空"); + if (points < 0 || points > 100) + throw new ArgumentOutOfRangeException("分数必须在0-100之间"); + } public override string ToString() { // TODO: 返回格式化的成绩信息 - + return $"科目: {Subject}, 分数: {Points:F1}"; } } @@ -83,31 +110,47 @@ public class StudentManager : IRepository { // TODO: 定义私有字段存储学生列表 // 提示:使用List存储 - + private List students = new List(); + public void Add(Student item) { // TODO: 实现添加学生的逻辑 // 1. 参数验证 // 2. 添加到列表 - + if (item == null) + throw new ArgumentNullException(nameof(item), "学生对象不能为空"); + if (students.Contains(item)) + throw new InvalidOperationException($"学号为{item.StudentId}的学生已存在"); + + 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循环查找符合条件的学生 + List result = new List(); + foreach (var student in students) + { + if (predicate(student)) + { + result.Add(student); + } + } + return result; } @@ -115,7 +158,15 @@ public List Find(Func predicate) public List GetStudentsByAge(int minAge, int maxAge) { // TODO: 使用foreach循环和if判断实现年龄范围查询 - + List result = new List(); + foreach (var student in students) + { + if (student.Age >= minAge && student.Age <= maxAge) + { + result.Add(student); + } + } + return result; } } @@ -124,7 +175,8 @@ public class ScoreManager { // TODO: 定义私有字段存储成绩字典 // 提示:使用Dictionary>存储 - + private Dictionary> scores = new Dictionary>(); + public void AddScore(string studentId, Score score) { @@ -132,33 +184,78 @@ public void AddScore(string studentId, Score score) // 1. 参数验证 // 2. 初始化学生成绩列表(如不存在) // 3. 添加成绩 - + if (string.IsNullOrWhiteSpace(studentId)) + throw new ArgumentException("学号不能为空"); + if (score == null) + throw new ArgumentNullException(nameof(score)); + + if (!scores.ContainsKey(studentId)) + { + scores[studentId] = new List(); + } + scores[studentId].Add(score); + } public List GetStudentScores(string studentId) { // TODO: 获取指定学生的所有成绩 - + return new List(scores[studentId]); } public double CalculateAverage(string studentId) { // TODO: 计算指定学生的平均分 // 提示:使用foreach循环计算总分,然后除以科目数 - + var studentScores = GetStudentScores(studentId); + if (studentScores.Count == 0) + return 0; + + double total = 0; + foreach (var score in studentScores) + { + total += score.Points; + } + return total / studentScores.Count; + } // TODO: 使用模式匹配实现成绩等级转换 public Grade GetGrade(double score) { - + if (score >= 90) + return Grade.A; + else if (score >= 80) + return Grade.B; + else if (score >= 70) + return Grade.C; + else if (score >= 60) + return Grade.D; + else + return Grade.F; + } public List<(string StudentId, double Average)> GetTopStudents(int count) { // TODO: 使用简单循环获取平均分最高的学生 // 提示:可以先计算所有学生的平均分,然后排序取前count个 - + var studentAverages = new List<(string StudentId, double Average)>(); + foreach (var studentId in scores.Keys) + { + studentAverages.Add((studentId, CalculateAverage(studentId))); + } + + var sortedStudentAverages = studentAverages.OrderByDescending(s => s.Average).ToList(); + + // 取前count名 + var result = new List<(string, double)>(); + for (int i = 0; i < Math.Min(count, studentAverages.Count); i++) + { + result.Add(studentAverages[i]); + } + return result; + } public Dictionary> GetAllScores() @@ -177,7 +274,16 @@ 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}"); + } + } + Console.WriteLine($"学生数据已成功保存到 {filePath}"); + } catch (Exception ex) { @@ -194,7 +300,18 @@ public List LoadStudentsFromFile(string filePath) try { // 在这里实现文件读取逻辑 - + using (StreamReader reader = new StreamReader(filePath)) + { + string? header = reader.ReadLine(); + string? line; + + while ((line = reader.ReadLine()) != null) + { + string[] parts = line.Split(','); + } + } + Console.WriteLine($"从 {filePath} 成功读取学生数据"); + } catch (Exception ex) { @@ -241,22 +358,49 @@ static void Main(string[] args) // 3. 测试年龄范围查询 Console.WriteLine("\n3. 查找年龄在19-20岁的学生:"); // TODO: 调用GetStudentsByAge方法并显示结果 - + var ageRangeStudents = studentManager.GetStudentsByAge(19, 20); + foreach (var student in ageRangeStudents) + { + Console.WriteLine(student); + } // 4. 显示学生成绩统计 Console.WriteLine("\n4. 学生成绩统计:"); // TODO: 遍历所有学生,显示其成绩、平均分和等级 - + foreach (var student in studentManager.GetAll()) + { + Console.WriteLine($"{student.Name} 的成绩 :"); + var scores = scoreManager.GetStudentScores(student.StudentId); + foreach (var score in scores) + { + Console.WriteLine(score); + } + double avg = scoreManager.CalculateAverage(student.StudentId); + Grade grade = scoreManager.GetGrade(avg); + Console.WriteLine($"平均分: {avg}, 等级: {grade}"); + Console.WriteLine(); + } + // 5. 显示排名(简化版) Console.WriteLine("\n5. 平均分最高的学生:"); // TODO: 调用GetTopStudents(1)方法显示第一名 - + var top = scoreManager.GetTopStudents(1).First(); + Console.WriteLine($"第一名: 学号: {top.StudentId}, 平均分: {top.Average}"); + + // 6. 文件操作 Console.WriteLine("\n6. 数据持久化演示:"); // TODO: 保存和读取学生文件 - + string filePath = "students.csv"; + dataManager.SaveStudentsToFile(studentManager.GetAll(), filePath); + var loadedStudents = dataManager.LoadStudentsFromFile(filePath); + Console.WriteLine("读取到的学生信息:"); + foreach (var student in loadedStudents) + { + Console.WriteLine(student); + } } catch (Exception ex) diff --git a/Homework/obj/Debug/net9.0/.NETCoreApp,Version=v9.0.AssemblyAttributes.cs b/Homework/obj/Debug/net9.0/.NETCoreApp,Version=v9.0.AssemblyAttributes.cs deleted file mode 100644 index feda5e9..0000000 --- a/Homework/obj/Debug/net9.0/.NETCoreApp,Version=v9.0.AssemblyAttributes.cs +++ /dev/null @@ -1,4 +0,0 @@ -// -using System; -using System.Reflection; -[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v9.0", FrameworkDisplayName = ".NET 9.0")] diff --git a/Homework/obj/Debug/net9.0/Homework.AssemblyInfo.cs b/Homework/obj/Debug/net9.0/Homework.AssemblyInfo.cs deleted file mode 100644 index aa6f005..0000000 --- a/Homework/obj/Debug/net9.0/Homework.AssemblyInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -using System; -using System.Reflection; - -[assembly: System.Reflection.AssemblyCompanyAttribute("Homework")] -[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] -[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] -[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] -[assembly: System.Reflection.AssemblyProductAttribute("Homework")] -[assembly: System.Reflection.AssemblyTitleAttribute("Homework")] -[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] - -// 由 MSBuild WriteCodeFragment 类生成。 - diff --git a/Homework/obj/Debug/net9.0/Homework.AssemblyInfoInputs.cache b/Homework/obj/Debug/net9.0/Homework.AssemblyInfoInputs.cache deleted file mode 100644 index 497cd46..0000000 --- a/Homework/obj/Debug/net9.0/Homework.AssemblyInfoInputs.cache +++ /dev/null @@ -1 +0,0 @@ -92fcf719969c7f59361926c468f07a76ab2866f8147167aa553b98c3b9d7ed15 diff --git a/Homework/obj/Debug/net9.0/Homework.GeneratedMSBuildEditorConfig.editorconfig b/Homework/obj/Debug/net9.0/Homework.GeneratedMSBuildEditorConfig.editorconfig deleted file mode 100644 index 5bddca1..0000000 --- a/Homework/obj/Debug/net9.0/Homework.GeneratedMSBuildEditorConfig.editorconfig +++ /dev/null @@ -1,15 +0,0 @@ -is_global = true -build_property.TargetFramework = net9.0 -build_property.TargetPlatformMinVersion = -build_property.UsingMicrosoftNETSdkWeb = -build_property.ProjectTypeGuids = -build_property.InvariantGlobalization = -build_property.PlatformNeutralAssembly = -build_property.EnforceExtendedAnalyzerRules = -build_property._SupportedPlatformList = Linux,macOS,Windows -build_property.RootNamespace = Homework -build_property.ProjectDir = C:\Users\ms169\Desktop\Homework\Homework\ -build_property.EnableComHosting = -build_property.EnableGeneratedComInterfaceComImportInterop = -build_property.EffectiveAnalysisLevelStyle = 9.0 -build_property.EnableCodeStyleSeverity = diff --git a/Homework/obj/Debug/net9.0/Homework.GlobalUsings.g.cs b/Homework/obj/Debug/net9.0/Homework.GlobalUsings.g.cs deleted file mode 100644 index 8578f3d..0000000 --- a/Homework/obj/Debug/net9.0/Homework.GlobalUsings.g.cs +++ /dev/null @@ -1,8 +0,0 @@ -// -global using global::System; -global using global::System.Collections.Generic; -global using global::System.IO; -global using global::System.Linq; -global using global::System.Net.Http; -global using global::System.Threading; -global using global::System.Threading.Tasks; diff --git a/Homework/obj/Debug/net9.0/Homework.assets.cache b/Homework/obj/Debug/net9.0/Homework.assets.cache deleted file mode 100644 index e69f95a..0000000 Binary files a/Homework/obj/Debug/net9.0/Homework.assets.cache and /dev/null differ diff --git a/Homework/obj/Homework.csproj.nuget.dgspec.json b/Homework/obj/Homework.csproj.nuget.dgspec.json deleted file mode 100644 index 2ef35da..0000000 --- a/Homework/obj/Homework.csproj.nuget.dgspec.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "format": 1, - "restore": { - "C:\\Users\\ms169\\Desktop\\Homework\\Homework\\Homework.csproj": {} - }, - "projects": { - "C:\\Users\\ms169\\Desktop\\Homework\\Homework\\Homework.csproj": { - "version": "1.0.0", - "restore": { - "projectUniqueName": "C:\\Users\\ms169\\Desktop\\Homework\\Homework\\Homework.csproj", - "projectName": "Homework", - "projectPath": "C:\\Users\\ms169\\Desktop\\Homework\\Homework\\Homework.csproj", - "packagesPath": "C:\\Users\\ms169\\.nuget\\packages\\", - "outputPath": "C:\\Users\\ms169\\Desktop\\Homework\\Homework\\obj\\", - "projectStyle": "PackageReference", - "fallbackFolders": [ - "C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages" - ], - "configFilePaths": [ - "C:\\Users\\ms169\\AppData\\Roaming\\NuGet\\NuGet.Config", - "C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config", - "C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config" - ], - "originalTargetFrameworks": [ - "net9.0" - ], - "sources": { - "C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {}, - "https://api.nuget.org/v3/index.json": {} - }, - "frameworks": { - "net9.0": { - "targetAlias": "net9.0", - "projectReferences": {} - } - }, - "warningProperties": { - "warnAsError": [ - "NU1605" - ] - }, - "restoreAuditProperties": { - "enableAudit": "true", - "auditLevel": "low", - "auditMode": "direct" - }, - "SdkAnalysisLevel": "9.0.200" - }, - "frameworks": { - "net9.0": { - "targetAlias": "net9.0", - "imports": [ - "net461", - "net462", - "net47", - "net471", - "net472", - "net48", - "net481" - ], - "assetTargetFallback": true, - "warn": true, - "frameworkReferences": { - "Microsoft.NETCore.App": { - "privateAssets": "all" - } - }, - "runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\9.0.201/PortableRuntimeIdentifierGraph.json" - } - } - } - } -} \ No newline at end of file diff --git a/Homework/obj/Homework.csproj.nuget.g.props b/Homework/obj/Homework.csproj.nuget.g.props deleted file mode 100644 index 9026052..0000000 --- a/Homework/obj/Homework.csproj.nuget.g.props +++ /dev/null @@ -1,16 +0,0 @@ - - - - True - NuGet - $(MSBuildThisFileDirectory)project.assets.json - $(UserProfile)\.nuget\packages\ - C:\Users\ms169\.nuget\packages\;C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages - PackageReference - 6.13.1 - - - - - - \ No newline at end of file diff --git a/Homework/obj/Homework.csproj.nuget.g.targets b/Homework/obj/Homework.csproj.nuget.g.targets deleted file mode 100644 index 3dc06ef..0000000 --- a/Homework/obj/Homework.csproj.nuget.g.targets +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Homework/obj/project.assets.json b/Homework/obj/project.assets.json deleted file mode 100644 index 907663e..0000000 --- a/Homework/obj/project.assets.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "version": 3, - "targets": { - "net9.0": {} - }, - "libraries": {}, - "projectFileDependencyGroups": { - "net9.0": [] - }, - "packageFolders": { - "C:\\Users\\ms169\\.nuget\\packages\\": {}, - "C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages": {} - }, - "project": { - "version": "1.0.0", - "restore": { - "projectUniqueName": "C:\\Users\\ms169\\Desktop\\Homework\\Homework\\Homework.csproj", - "projectName": "Homework", - "projectPath": "C:\\Users\\ms169\\Desktop\\Homework\\Homework\\Homework.csproj", - "packagesPath": "C:\\Users\\ms169\\.nuget\\packages\\", - "outputPath": "C:\\Users\\ms169\\Desktop\\Homework\\Homework\\obj\\", - "projectStyle": "PackageReference", - "fallbackFolders": [ - "C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages" - ], - "configFilePaths": [ - "C:\\Users\\ms169\\AppData\\Roaming\\NuGet\\NuGet.Config", - "C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config", - "C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config" - ], - "originalTargetFrameworks": [ - "net9.0" - ], - "sources": { - "C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {}, - "https://api.nuget.org/v3/index.json": {} - }, - "frameworks": { - "net9.0": { - "targetAlias": "net9.0", - "projectReferences": {} - } - }, - "warningProperties": { - "warnAsError": [ - "NU1605" - ] - }, - "restoreAuditProperties": { - "enableAudit": "true", - "auditLevel": "low", - "auditMode": "direct" - }, - "SdkAnalysisLevel": "9.0.200" - }, - "frameworks": { - "net9.0": { - "targetAlias": "net9.0", - "imports": [ - "net461", - "net462", - "net47", - "net471", - "net472", - "net48", - "net481" - ], - "assetTargetFallback": true, - "warn": true, - "frameworkReferences": { - "Microsoft.NETCore.App": { - "privateAssets": "all" - } - }, - "runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\9.0.201/PortableRuntimeIdentifierGraph.json" - } - } - } -} \ No newline at end of file diff --git a/Homework/obj/project.nuget.cache b/Homework/obj/project.nuget.cache deleted file mode 100644 index d182034..0000000 --- a/Homework/obj/project.nuget.cache +++ /dev/null @@ -1,8 +0,0 @@ -{ - "version": 2, - "dgSpecHash": "Mpgpv19Q1hE=", - "success": true, - "projectFilePath": "C:\\Users\\ms169\\Desktop\\Homework\\Homework\\Homework.csproj", - "expectedPackageFiles": [], - "logs": [] -} \ No newline at end of file