CSharp 使用另一个列表及其嵌套列表筛选具有 LINQ 查询的列表

CSharp Filtering A List With A LINQ query Using Another List And Its Nested List

提问人:DorD 提问时间:10/10/2021 更新时间:10/10/2021 访问量:72

问:

我正在尝试对课程列表使用 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

我不希望控制台向我显示课程名称三次(仅一次),如上面的代码所示。

有没有办法解决这个问题?

谢谢 多尔

C# 列表 LINQ 嵌套列表

评论

0赞 Vivek Nuna 10/10/2021
您可以在循环中使用 thi ...或CoursesList.Distinct(p => p.CourseName)group p by new {p.CourseName} into groupBy select groupBy.FirstOrDefault();
0赞 Ermiya Eskandary 10/10/2021
你是说私有列表吗<学生>学生列表=新列表<学生>{};而不是私有列表< Course> StudentsList = new List<Student>{};?

答:

0赞 Ermiya Eskandary 10/10/2021 #1

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

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

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

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