【问题标题】:CSharp Filtering A List With A LINQ query Using Another List And Its Nested ListCSharp使用另一个列表及其嵌套列表过滤带有LINQ查询的列表
【发布时间】: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 =&gt; 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


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 2017-11-29
    • 2021-06-12
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    相关资源
    最近更新 更多