LINQ多列表连接

时间:2016-05-19 12:40:55

标签: c# linq

我正在学习LINQ,我试图设置一个更复杂的情况来管理LINQ。嗯......我被卡住了。

我设置的是3个班级

班级类:

class Class
{
    public int Number { get; private set; }

    public Class(int number)
    {
        Number = number;
    }
}

老师班:

class Teacher
{
    public string Name { get; private set; }

    public int Class { get; set; }

    public Teacher(string name, int Class)
    {
        Name = name;
        this.Class = Class;
    }
}

学生班:

class Student
{
    public string Name { get; private set; }
    public int Class { get; set; }

    public Student(string name, int Class)
    {
        Name = name;
        this.Class = Class;
    }
}

我想要做的是将这3个课程加在一起,以获得包含教师及其学生的学校课程列表。

我试过了:

var classWithTeacherAndStudent =
            from Class in classes
            join Teacher in teacher
                on Class.Number equals Teacher.Class
            let teacherClass = new {Class, Teacher}
            join student in students
                on teacherClass.Class.Number equals student.Class
                into entireClass
            select new
            {

            };

列表中有许多班级,教师和学生对象。

1 个答案:

答案 0 :(得分:1)

联接似乎是正确的。您可以只选择所有值为匿名类型,因此每个条目都有一个类,它的老师和所有学生。

var classWithTeacherAndStudent =
from Class in classes
join Teacher in teacher
    on Class.Number equals Teacher.Class
let teacherClass = new { Class, Teacher }
join student in students
    on teacherClass.Class.Number equals student.Class
    into entireClass
select new
{
    teacherClass.Teacher, teacherClass.Class, entireClass
};

foreach (var entry in classWithTeacherAndStudent)
{
    Console.WriteLine("teacher: {0}, class: {1}", entry.Teacher.Name, entry.Class.Number);
    foreach (var student in entry.entireClass)
    {
        Console.WriteLine(student.Name);
    }
}