首页 > 解决方案 > CSharp Filtering A List With A LINQ query Using Another List And Its Nested List

问题描述

I am trying to use a LINQ query on a list of courses to filter each course according to the students in the class' student list with the size of the student's grades average. The students' grades are a list of doubles.

This is a simplified structure of the classes I am using for the code:

class Course{
    private string CourseName;
    private List<Course> StudentsList = new List<Student>{};

//This is a nested class
    public class Student{
        private string StudentName;
        private List<double> StudentGrades;
   }
}

The simplified code(assume each list and nested list is already initialized):

//The function GetAverage() takes the average of the student, calculates, and returns it.
//The code is inside the course class in a method called Q1.
var Above60 = from course in CoursesList
              from student in course.StudentList
              where student.GetAverage() > 60
              select course;

foreach(course in CoursesList){
   Console.WriteLine($"{course.CourseName});
}

Actual result(below are just the courses' names):

C#
C#
C#
SQL
SQL
SQL
JAVA 
JAVA
JAVA

I do not want the console to display to me the courses' names three times(only one time) as is shown in the code above.

Is there a way I can fix this?

thank you very much, Dor

标签: c#listlinqnested-lists

解决方案


要从 中过滤掉具有重复名称的课程CoursesList,请使用.DistinctLINQ 扩展方法。

这应该会产生预期的输出:

var uniqueCourseNames = CoursesList.Distinct(c => c.CourseName);

foreach(course in uniqueCourseNames){
   Console.WriteLine($"{course.CourseName});
}

推荐阅读