c# - 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
解决方案
要从 中过滤掉具有重复名称的课程CoursesList
,请使用.Distinct
LINQ 扩展方法。
这应该会产生预期的输出:
var uniqueCourseNames = CoursesList.Distinct(c => c.CourseName);
foreach(course in uniqueCourseNames){
Console.WriteLine($"{course.CourseName});
}
推荐阅读
- html - HTML 视频未出现在页面上
- python - 关于爬楼梯记忆自上而下方法的问题
- c++ - 嵌套类上的 __declspec(dllexport)
- bash - 通过 ssh.Client 上传文件,如果不存在则创建路径
- r - R dplyr中的量化列
- html - 一旦填写了Angular,如何使输入字段恢复为“原始/未触及”?
- apache-spark - Spark - 根据 spark 版本加载 jar
- java - 我可以将一个图形拖到另一个图形上并更改它吗?(爪哇)
- javascript - ReactJS 面临关于清除复选框选中状态的问题
- php - 如何镜像使用嵌套 for 循环制作的这个三角形