I need to output to the console the name of the group and the average score for each subject. But in Console.WriteLine Group and groupAverageMath are underlined with error "The name "Group"/"groupAverageMath" does not exist in the current context"
static void BestGroupAverage()
{
List<Student> students = ListManager.LoadSampleData();
var GroupAverageMath =
from student in students
group student by student.Group into studentGroup
select new
{
Group = studentGroup.Key,
groupAverageMath = studentGroup.Average(x => x.Math),
};
Console.WriteLine("\nGgroup with the best GPA in Math: " Group groupAverageMath);
Console.ReadLine();
}
CodePudding user response:
Here's a very explicit solution. You didn't provide a definition of your Student
class, so I had to:
public class Student
{
public string Name { get; set; }
public string Group { get; set; }
public decimal Math { get; set; }
public Student (string name, string group, decimal mathGrade)
{
Name = name;
Group = group;
Math = mathGrade;
}
}
Then, with very explicit steps so you can understand. Note that I provided data (because, again, you did not):
public static void Test()
{
//this is what you need to do in a question, provide
//enough data so others can reproduce your issue
var students = new List<Student>
{
new Student("A", "blue", 42),
new Student("B", "blue", 88.5m),
new Student("C", "green", 99m),
new Student("D", "blue", 78.5m),
new Student("E", "red", 66.6m),
new Student("X", "red", 90),
new Student("Y", "green", 28),
new Student("Z", "blue", 80),
};
var groupAverageMath =
from student in students
group student by student.Group into studentGroup
select new
{
Group = studentGroup.Key,
GroupAverageMath = studentGroup.Average(x => x.Math),
};
var bestMathGrade = groupAverageMath.Max(gr => gr.GroupAverageMath);
var bestGroups = groupAverageMath.Where(g => g.GroupAverageMath ==bestMathGrade);
var bestGroup = bestGroups.FirstOrDefault();
Console.WriteLine($"\nGroup with the best GPA in Math: {bestGroup.Group} score: {bestGroup.GroupAverageMath}");
Console.ReadLine();
}
I get the groups. Then I get the maximum group average. Then I find out which group or groups got that average. Then I pick the first one.
This results in:
Group with the best GPA in Math: red score: 78.3