我有以下两种方法
/// <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;
}
这些方法都不起作用,我试图找出我出错的地方以及我需要做些什么来获得我想要实现的目标。
有什么建议吗?
答案 0 :(得分:1)
第一种方法应该使用此方法: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告诉方法如何处理这些组。在这种情况下,对于每个组,我创建一个元组,其中包含每个组中学生的级别和计数。
您的返回值应更改为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);
}