【问题标题】:C# How to create a generic list of students and grades and access thoseC#如何创建学生和成绩的通用列表并访问这些
【发布时间】:2014-10-10 23:25:03
【问题描述】:

我正在用 C# 做一些应该很容易的事情。我需要一个临时存储系统来存储未知数量的学生和每个学生的未知数量的属性。

我基本上得到了未知数量的学生,然后对每个学生进行查询以返回他们的成绩和其他可能与任何其他学生不同的信息。

  • 学生 1: 姓名:约翰 姓名:Doe 数学 1010:一个 数学 2020:B 数学 3010:B+ 工程 1010:A-

  • 学生 2: 姓名:四月 姓名:约翰逊 地质 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);
}

【问题讨论】:

  • 好。你的问题到底是什么?
  • 这个问题有点模棱两可——你是否将属性保存在Student 类中(在这种情况下,每个学生都会有一个List 或一个Dictionary)还是你想要某种DictionaryStudent 对象映射到属性?

标签: c# generics


【解决方案1】:

你可以像这样声明一个学生类:

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

        }

【讨论】:

    【解决方案2】:

    你的学生需要一个领域

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

    有了它,您可以存储未知数量的属性。

    然后循环

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

    当然,您也可以与固定属性混合使用。 为了获得良好的编码,您应该使用属性和辅助成员函数来实现。我的例子很基础。

    【讨论】:

    • 不应该是foreach 而不是for
    • 你是对的。谢谢。我混淆了一些 objc js 语法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多