I have the following simple data structure. A list of students, each with a unique ID. Each student has a list of courses they are enrolled in. Courses also have unique IDs, but will be members of multiple studentCourses lists (as each course is enrolled in by multiple students).
I’m trying to find a particular grade value, by studentId and courseId. I’m using the linq query below. I’m still a little shakey with my linq, and was wondering if the query i’ve written is correct? It does work correctly, but could it be changed to be more elegant/readable?
class Student {
int studentId;
string studentName;
List<Course> studentCourses;
}
class Course {
int courseId;
string courseName;
int grade;
}
List<Student> students = new List<Student>();
//populate list.
int studentGrade = students
.Where(c => c.studentId == 1)
.Select(c => c.studentCourses.FirstOrDefault(a => a.courseId == 1).grade)
.FirstOrDefault();
1 Answer