【发布时间】:2021-11-29 12:21:56
【问题描述】:
我正在尝试对课程列表使用 LINQ 查询,以根据班级学生列表中的学生以及学生平均成绩的大小来过滤每门课程。 学生的成绩是双打列表。
这是我用于代码的类的简化结构:
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 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});
}
实际结果(以下仅为课程名称):
C#
C#
C#
SQL
SQL
SQL
JAVA
JAVA
JAVA
我不希望控制台向我显示课程名称三次(仅一次),如上面的代码所示。
有什么办法可以解决这个问题吗?
非常感谢, 多尔
【问题讨论】:
-
你可以在循环中使用 thi
CoursesList.Distinct(p => p.CourseName)...或group p by new {p.CourseName} into groupBy select groupBy.FirstOrDefault(); -
你的意思是私人名单Student > StudentsList = new List
{};而不是私有列表Course > StudentsList = new List {};?
标签: c# list linq nested-lists