我需要將組的名稱和每個科目的平均分數輸出到控制臺。但在Console.WriteLine Group和groupAverageMath下劃線顯示錯誤“當前背景關系中不存在名稱“Group”/“groupAverageMath””
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();
}
uj5u.com熱心網友回復:
這是一個非常明確的解決方案。你沒有提供你的Student類的定義,所以我不得不:
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;
}
}
然后,使用非常明確的步驟,以便您可以理解。請注意,我提供了資料(因為您再次沒有提供):
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();
}
我得到了團體。然后我得到最大的組平均值。然后我找出哪個或哪個組獲得了這個平均值。那我選第一個。
這導致:
Group with the best GPA in Math: red score: 78.3
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/377623.html
