如何将多个 属性 添加到 IEnumerable<Student> 的列表中

How to add multiple property into a List of IEnumerable<Student>

我创建了一个 class Student 并且在 class 中它具有这些属性:

      class Student: IEnumerable<Student>
    {
    private int age =0 ;
    private string name ="";
    private bool isAdult = false;


List<Student> StudentList = new List<Student>();

        public Student this[int index]
        {
            get { return StudentList [index]; }
            set { StudentList .Insert(index, value); }
        }

        public IEnumerator<Student> GetEnumerator()
        {
            return StudentList.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }


    public string Name 
            {
                get { return name ; }
                set { name = value; }
            } 

    public int Age 
            {
                get { return age ; }
                set { age = value; }
            } 
    public bool IsAdult 
            {
                get { return isAdult ; }
                set { isAdult = value; }
            } 

    }

现在我要做的是将 oracle 查询的结果加载到新的学生列表中

//...
try

List < Student > StudentList = new List < Student > (); {

    OracleCommand command = new OracleCommand(sqlQuery, connection);
    OracleDataReader oracleDataReader = command.ExecuteReader();
    while (oracleDataReader.Read()) {

        age = Convert.Int64(oracleDataReader["age"]);
        name = oracleDataReader["name"].toString();
        isAdult = Convert.boolean(oracleDataReader["isAdult"])
    }
}
//...

假设查询 returns 100 students 和 student class 实际上包含 10-15 个属性,我只以 3(name,age,isAdult)为例来解释我的问题

是否可以在 StudentList 中加载查询返回的每一行?

主要问题是您的 Student class 试图实现 IEnumerable<Student> 接口。那没有意义。 IEnumerable<Student> 接口应该由其他一些 class 实现。或者您使用实现此接口的 List<...> class。 Student class 应仅包含您要保存的有关学生的值。

假设您在 while 循环的某处只有一个 List<Student> 对象,您可以遍历数据库中的行,创建一个新的 Student 对象并将其添加到列表中。

IList<Student> students = new List<Student>();
while (oracleDataReader.Read()) {

    int age = Convert.Int64(oracleDataReader["age"]);
    string name = oracleDataReader["name"].toString();
    bool isAdult = Convert.boolean(oracleDataReader["isAdult"]);

    Student student = new Student {
        age = age,
        name = name,
        isAdult = isAdult
    };
    students.Add(student);
}

然后您可以使用 students 列表。