2014-10-10 38 views
0

我正在努力与C#的东西,应该很容易。我需要一个临时存储系统来处理未知数量的学生,并且每个学生都有一个未知数量的属性。C#如何创建一个学生和成绩的通用列表,并访问这些

我基本上是收到一个未知数的学生,然后对每个学生做一个查询,以返回他们的成绩和其他信息,这些信息可能与其他任何学生不同。

  • 学生1: 姓名:John 姓:Doe的 数学1010:甲 数学2020:乙 数学3010:B + 主机1010:A-

  • 学生2: 名称:四月 姓:约翰逊 地质1000:C 数学1010:乙 等等

然后最后,我只需要遍历每个学生并输出他们的信息。

我发现这个例子对每个学生有一组已知的项目很有帮助,但我想我需要为每个学生列出一个列表,而且我不知道如何制作“主”列表。我可以算出数组,但工作泛型对我来说是新的。

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); 
} 
+4

好。你的问题到底是什么? – 2014-10-10 15:11:54

+1

这个问题有点含糊不清 - 你是否将属性保存在'Student'类中(在这种情况下,每个学生都有一个'List'或者'Dictionary'),或者你想要某种'Dictionary'来映射Student对象属性? – UnholySheep 2014-10-10 15:12:17

回答

0

你可以声明一个学生类,如:

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); 
      } 

     } 
0

你的学生需要一个场

class Student 
{ 
    public Dictionary<string, object> Attributes = new Dictionary<string, object>(); 
} 

这样,您可以存储您的未知数量的属性。

然后循环

foreach(var student in studentsList) 
{ 
    Console.WriteLine("attr: " + student.Attributes["attr"]); 
} 

当然你也可以用固定属性混合太。 对于良好的编码,您应该使用属性和帮助器成员函数来实现。我的例子是非常基本的。

+1

应该不是'foreach'而不是'for'? – UnholySheep 2014-10-10 15:19:31

+0

你是对的。谢谢。我混淆了一些objc js语法。 – Tuan 2014-10-10 15:21:13

相关问题