MST
星途 面试题库

面试题:C#中LINQ的复杂查询与投影

给定两个类,Student类包含属性Id(int)、Name(string)、Scores(List<int>);Course类包含属性Id(int)、CourseName(string)。假设有一个List<Student> students和List<Course> courses。学生的Scores列表中存储了他们在不同课程上的成绩,成绩的顺序与courses列表中的课程顺序对应。请使用LINQ查询出每个学生的姓名、课程名称以及对应的成绩,并以一个新的匿名类型(包含StudentName, CourseName, Score)的列表形式返回结果。
36.4万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
var result = from student in students
             from score in student.Scores.Select((s, index) => new { Score = s, CourseIndex = index })
             join course in courses on score.CourseIndex equals courses.IndexOf(course)
             select new { 
                 StudentName = student.Name, 
                 CourseName = course.CourseName, 
                 Score = score.Score 
             };
return result.ToList();