在列表中插入列表

时间:2014-04-26 00:12:27

标签: c#

截至目前,我有两个列表,一个包含学生列表,另一个包括教室列表,我想要做的是,在创建教室和创建学生列表之后,我将如何进行关于将学生名单复制到教室。

假设我创建了一个名为“化学”的教室,一旦我输入学生列表,就会将其添加到教室列表(元素0),如何在课堂中复制/放置该学生列表。

我理解这个问题是否有点模糊,基本上我可以动态创建教室,只需将学生列表添加到我创建的任何教室。

感谢您的时间。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace P3_O_O_P
{
    public class Classroom
    {
        public List<Module> roomList;

        public Classroom()
        {
            roomList = new List<Module>();
        }

        public void createClassRoom(Module objMod)
        {
            Console.Write("\nEnter room name: ");
            objMod.ModuleName = Console.ReadLine();

            Console.Write("\nEnter a module I.D. code: ");
            objMod.ModuleID = Convert.ToDouble(Console.ReadLine());

            roomList.Add(new Module(objMod.ModuleName, objMod.ModuleID));
        }

        public void classList()
        {
            foreach (var module in roomList)
            {
                Console.Write("\nModule: " + module);
            }
        }
    }
}

public void addStudent(Student student, Module objMod, Classroom objClassroom, int mark)
    {
        objMod.registerList.Add(new Registration(student, mark));

        objMod.Enrol(student, Mark, objClassroom);
    }

2 个答案:

答案 0 :(得分:2)

我修改Classroom课程以包含List<Student>

将setter设为私有,以便列表不能设置为null或实例化为Classroom类之外的新列表。公共吸气者允许您拨打Add()Remove()

public class Classroom
{
    ...
    public List<Student> Students { get; private set; }

    public Classroom()
    {
        ...
        Students = new List<Student>();
    }

    ...
}

然后添加到方法内的列表中:

public void addStudent(Student student, Module objMod, Classroom objClassroom, int mark)
{
    ...

    objClassroom.Students.Add(student);
}

答案 1 :(得分:0)

也许就像你在数据库中那样做,例如创建关联类型列表

public class StudentsClassrooms
{
    public int StudentId { get; set; }
    public int ClassroomId { get; set; }
}

public List<StudentsClassrooms> associations = new List<StudentsClassrooms>();

然后你可以将它们连接在一起并用Linq查询它们。