合并两个列表对象列表

时间:2018-12-20 07:45:21

标签: c# linq linq-to-sql

我有两个班级,我想两个将这两个列表合并为一个列表。

public class School
{
    public string Name { get; set; }
    public List<ClassRoom> ClassRooms { get; set; }
}
public class ClassRoom
{
    public int ClassRoomID { get; set; }
    public string GradeName { get; set; }
    public List<Student> Students { get; set; }
    public List<Teacher> Teachers { get; set; }
}
public class Teacher
{
    public int TeacherID { get; set; }
    public string Name { get; set; }
    public List<Adress> Adresses { get; set; }
}
public class Student
{
    public int StudentID { get; set; }
    public string Name { get; set; }
    public List<Adress> Adresses { get; set; }
}
public class Adress
{
    public string DetailedAddress { get; set; }
    public string ZipCode { get; set; }
}

这是我尝试过的

    School school1 = new School();
    School school2 = new School();

    school1.Name = "new NAme";
    school1.ClassRooms.AddRange(school2.ClassRooms);

我面临的问题是内部列表未正确添加。 合并列表没有 列出学生 列出教师

这两个都是空的。

1 个答案:

答案 0 :(得分:-1)

您必须启动所有列表。

School school1 = new School();
school1.ClassRooms = new List<ClassRoom>();

school1.ClassRooms.Students = new List<Student>();
school1.ClassRooms.Students.Adresses = new List<Adresses>();

school1.ClassRooms.Teachers = new List<Teachers>();
school1.ClassRooms.Teachers.Adresses = new List<Adresses>();

您也必须启动学校2。然后,您可以添加。否则它将变为空。最好使用构造函数来做到这一点。