C#如何创建学生和成绩的通用列表并访问这些列表
本文关键字:列表 访问 何创建 创建 | 更新日期: 2023-09-27 18:26:13
我正在为一些本应非常简单的事情与C#作斗争。我需要一个临时存储系统,用于存储未知数量的学生和每个学生的未知数量的属性。
我基本上得到了未知数量的学生,然后对每个学生进行查询,以返回他们的成绩和其他信息,这些信息可能与其他学生不同。
-
学生1:姓名:John姓氏:Doe数学1010:A数学2020:B数学3010:B+Eng 1010:A-
-
学生2:姓名:April姓氏:Johnson地质学1000:C数学1010:B等等。
最后,我只需要遍历每个学生并输出他们的信息。
我发现这个例子适用于每个学生一组已知的项目,但我认为我需要为每个学生列出一个列表,我不知道如何制作"主"列表。我可以为数组找到它,但使用泛型对我来说是新的
List<Student> lstStudents = new List<Student>();
Student objStudent = new Student();
objStudent.Name = "Rajat";
objStudent.RollNo = 1;
lstStudents.Add(objStudent);
objStudent = new Student();
objStudent.Name = "Sam";
objStudent.RollNo = 2;
lstStudents.Add(objStudent);
//Looping through the list of students
foreach (Student currentSt in lstStudents)
{
//no need to type cast since compiler already knows that everything inside
//this list is a Student
Console.WriteLine("Roll # " + currentSt.RollNo + " " + currentSt.Name);
}
您可以声明一个学生类,如:
public class Student
{
private readonly Dictionary<string, object> _customProperties = new Dictionary<string, object>();
public Dictionary<string, object> CustomProperties { get { return _customProperties; } }
}
然后像这样使用:
List<Student> lstStudents = new List<Student>();
Student objStudent = new Student();
objStudent.CustomProperties.Add("Name", "Rajat");
objStudent.CustomProperties.Add("RollNo", 1);
lstStudents.Add(objStudent);
objStudent = new Student();
objStudent.CustomProperties.Add("Name", "Sam");
objStudent.CustomProperties.Add("RollNo", 2);
lstStudents.Add(objStudent);
foreach (Student currentSt in lstStudents)
{
foreach (var prop in currentSt.CustomProperties)
{
Console.WriteLine(prop.Key+" " + prop.Value);
}
}
您的学生需要一个字段
class Student
{
public Dictionary<string, object> Attributes = new Dictionary<string, object>();
}
有了它,您可以存储未知数量的属性。
然后循环
foreach(var student in studentsList)
{
Console.WriteLine("attr: " + student.Attributes["attr"]);
}
当然,你也可以与固定属性混合。为了获得良好的编码,您应该使用属性和辅助成员函数来实现。我的例子很基本。