查询和选择组中的 C# LINQ 查询

C# LINQ queries within queries and selecting groups

我有以下两种方法

/// <summary>
/// Reports the number of students in each ClassLevel designation
/// </summary>
/// <param name="students">The original collection of students</param>
/// <returns>A Dictionary where the key is the ClassLevel and the value is the number of students in that level</returns>
public static Dictionary<ClassLevel, int> StudentsPerClassLevel(this IEnumerable<Student> students)
{
     var query = students.GroupBy(student => student.Level).ToDictionary(x => x.Key, x => x.Count());
     return query;
}

/// <summary>
/// Determines which MaritalStatus has the highest average GPA
/// </summary>
/// <param name="students">The original collection of students</param>
/// <returns>The MaritalStatus value with the highest average GPA</returns>
public static MaritalStatus MaritalStatusWithHighestAverageGPA(this IEnumerable<Student> students)
{
        var query = students.GroupBy(s => s.Relationship).ToDictionary(x => x.Key, x => x.Average(g => g.GPA)).OrderByDescending(d => d.Value).First().Key;

        return query;
}

None 这些方法都行得通,我想弄清楚我哪里出错了,我需要做什么才能实现我想要实现的目标。

有什么建议吗?

第一种方法应该用这个方法:https://msdn.microsoft.com/en-us/library/vstudio/bb549393(v=vs.100).aspx

类似于:

return students.GroupBy(student => student.Level, (level, students) => new Tuple(level, students.Count())); 

抱歉,我无法对此进行测试,但基本上就像您的版本一样,我使用 lambda 表示按级别对所有学生进行分组。第二个 lambda 告诉方法如何处理这些组。在这种情况下,对于每个组,我正在创建一个元组,其中包含每个组中的级别和学生人数。

您的 return 值应更改为 IEnumerable<Tuple<ClassLevel, int>>,如果您愿意,可以轻松将其转换为字典。

我无法猜测在没有编译器的情况下解决你的第二种方法的语法。但是这个问题使用了Max:LINQ Using Max() to select a single row

编辑 这个版本似乎至少可以编译。希望您得出了类似的结论

    public static Dictionary<ClassLevel, int> StudentsPerClassLevel(this IEnumerable<Student> students)
    {
        return students.GroupBy(student => student.ClassLevel, 
            (level, s) => new Tuple<ClassLevel, int>(level, s.Count())).ToDictionary(t => t.Item1, t => t.Item2);

    }