Is there a way to remove for loops using linq to solve the problem i have
I want to get the subject and the amount of points for each student and each subject in this list:
IEnumerable<Student> students = new List<Student> {
new Student() {Id = 1, Name = "John", Age = 13},
new Student() {Id = 2, Name = "Mary", Age = 12},
new Student() {Id = 3, Name = "Anne", Age = 14}
};
I have a second list containing all the ratings and information about the subject:
IEnumerable<StudentScore> studentScores = new List<StudentScore> {
new StudentScore() {StudentId = 1, Subject = "Maths", Points = 54},
new StudentScore() {StudentId = 1, Subject = "Maths", Points = 32},
new StudentScore() {StudentId = 1, Subject = "English", Points = 55},
new StudentScore() {StudentId = 1, Subject = "English", Points = 54},
new StudentScore() {StudentId = 2, Subject = "Maths", Points = 44},
new StudentScore() {StudentId = 2, Subject = "Maths", Points = 37},
new StudentScore() {StudentId = 2, Subject = "English", Points = 59},
new StudentScore() {StudentId = 2, Subject = "English", Points = 64},
new StudentScore() {StudentId = 3, Subject = "Maths", Points = 53},
new StudentScore() {StudentId = 3, Subject = "Maths", Points = 72},
new StudentScore() {StudentId = 3, Subject = "English", Points = 54},
new StudentScore() {StudentId = 3, Subject = "English", Points = 59},
};
This is the solution I came across:
foreach (var student in students)
{
foreach (var studentScore in studentScores.Select(ss=>ss.Subject).Distinct())
{
Console.WriteLine("Name: " + student.Name + " Subject:" + studentScore + "Score: " + studentScores.Where(ss => ss.StudentId == student.Id)
.Where(ss => ss.Subject == studentScore)
.Sum(ss => ss.Points));
}
}