如何使用linq将列表中的列表转换为单个列表

时间:2018-07-12 14:32:20

标签: c# .net linq

如果我有如下对象:

public class Teacher
{
    public int TeacherId { get; set; }
    public string TeacherName { get; set; }
    public List<string> StudentNames { get; set; }
}

我想将其翻译成一个列表,其中每个老师的姓名与每个学生的姓名配对。

public class TeacherStudent
{

    public int TeacherId { get; set; }
    public string TeacherName { get; set; }
    public string StudentName { get; set; }

}

我知道我可以这样循环:

var teachers = new List<Teacher>();
teachers.Add(new Teacher() { TeacherId = 1, TeacherName = "Teacher1", StudentNames = new List<string>() { "Student1", "Student2" } });
teachers.Add(new Teacher() { TeacherId = 2, TeacherName = "Teacher2", StudentNames = new List<string>() { "Student3", "Student4", "Student5" } });
teachers.Add(new Teacher() { TeacherId = 3, TeacherName = "Teacher3", StudentNames = new List<string>() { "Student6", "Student7" } });


var teacherStudents = new List<TeacherStudent>();
foreach(var teacher in teachers)
{

    foreach (var studentName in teacher.StudentNames)
    {
        teacherStudents.Add(new TeacherStudent() { TeacherId = teacher.TeacherId, TeacherName = teacher.TeacherName, StudentName = studentName });
    }

}

似乎应该用linq来做到这一点,但我无法弄清楚。

1 个答案:

答案 0 :(得分:5)

您可以使用SelectMany

teachers.SelectMany(t =>
            t.StudentNames.Select(s => new TeacherStudent
            {
                TeacherId = t.TeacherId,
                TeacherName = t.TeacherName,
                StudentName = s
            }));