如何使用 linq 将列表中的列表转换为单个列表 [重复]
Posted
技术标签:
【中文标题】如何使用 linq 将列表中的列表转换为单个列表 [重复]【英文标题】:How to translate a list inside of a list to a single list with linq [duplicate] 【发布时间】:2018-07-12 14:32:19 【问题描述】:如果我有如下对象:
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 做到这一点,但我无法弄清楚。
【问题讨论】:
一个学生可以有多位老师吗?例如Student1
出现在Teacher1
和Teacher2
上?
【参考方案1】:
你可以使用SelectMany
:
teachers.SelectMany(t =>
t.StudentNames.Select(s => new TeacherStudent
TeacherId = t.TeacherId,
TeacherName = t.TeacherName,
StudentName = s
));
【讨论】:
以上是关于如何使用 linq 将列表中的列表转换为单个列表 [重复]的主要内容,如果未能解决你的问题,请参考以下文章